context:component-scan标签
Sprng容器通过context:component-scan标签扫描其base-package标签属性值指定的包及其子包内的所有的类并实例化被@Component、@Repository、@Service或@Controller等注解所修饰的类。
@Component:基本注解
@Respository:持久层(一般为dao层)注解
@Service:服务层或业务层(一般为service层)注解
@Controller:控制层(一般为controller层)注解
默认情况下Spring依据默认命名策略为通过注解实例化的对象命名:类名第一个字母小写. 也可以在注解中通过@Component、@Repository、@Service或@Controller 注解的value属性标识名称。
注意:使用context:component-scan标签需要添加spring-aop-4.3.10.RELEASE.jar包
context:component-scan子标签:
1、<context:include-filter> 子标签设定Spring容器扫描时仅扫描哪些expression指定的类,该子标签需要和context:component-scan父标签中的use-default-filters属性一起使用;
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- Spring容器扫描com.lq.book.imp基包,只有该包中注解为@Repository的类才会被实例化,此时需要将use-default-filters标签属性设置为false -->
<context:component-scan base-package="com.lq.book.imp" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
</beans>
2、<context:exclude-filter> 子标签设定Spring容器扫描时不扫描哪些expression指定的类;
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- Spring容器扫描com.lq.book.imp基包,只有该包中类注解非@Repository的类才会被实例化 -->
<context:component-scan base-package="com.lq.book.imp">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
</beans>