自动组件扫描
第一步:使用@Component标记类,使得spring容器能够识别为一个组件
@Component public class UserDAO { public void outPut(){ System.out.println("你好,这是一个自动扫描的demo"); }}第二步:在bean配置文件中启动扫描
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.main.autowrite.autoScanning" /></beans>第三步:提取bean并调用
@Test public void test(){ applicationContext context = new ClassPathXmlApplicationContext("com/main/autowrite/autoScanning/bean.xml"); UserDAO dao = (UserDAO)context.getBean("userDAO"); dao.outPut(); }输出结果为:
你好,这是一个自动扫描的demo自定义组件名称:使用@Service(“value”)
@Service("student") public class User{...} //调用方法 User user = (User)context.getBean("student");实际上,可以用以下四种注解来标识组件
@Component ——表示自动扫描组件@Service ——表示在业务层服务组件@Controller ——表示在表示层控制器组件@Repository ——表示在持久层DAO组件拦截器
允许特定组件可以通过
<context:component-scan base-package="com.yiibai" > <context:include-filter type="regex" expression="com.yiibai.customer.dao.*DAO.*" /> <context:include-filter type="regex" expression="com.yiibai.customer.services.*Service.*" /> </context:component-scan>说明:上述例子中将允许含有关键字DAO和Service的组件,在spring容器中注册,其他类型的组件都会被拦截掉
不允许特定组件通过
<context:component-scan base-package="com.yiibai" > <context:exclude-filter type="regex" expression="com.yiibai.customer.dao.*DAO.*" /> </context:component-scan>说明:上述例子中将拦截掉含有关键字DAO的组件,其他则pass
<context:component-scan base-package="com.yiibai.customer" > <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan>说明:不允许含有@Service的组件通过
注意:type为regex是指关键字,type为annoation是指特定注解
新闻热点
疑难解答