3、组件注册-@ComponentScan-自动扫描组件&指定扫描规则

3、组件注册-@ComponentScan-自动扫描组件&指定扫描规则

3.1 xml方式 benas.xml 导入context命名空间

<?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.xsd">

    <!--包扫描 , 只要标注了 @Controller 、@Service、@Repository、@Component的类 都会被扫描-->
    <context:component-scan base-package="com.hw.springannotation"></context:component-scan>

    <bean id="pension" class="com.hw.springannotation.beans.Pension">
        <property name="name" value="hw"></property>
        <property name="age" value="18"></property>
    </bean>
</beans>

3.2 注解方式

3.2.1 默认规则
@ComponentScan(value = "com.hw.springannotation")
3.2.2 指定排除扫描
@ComponentScan(value = "com.hw.springannotation",
        excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class, Service.class})}
)
3.2.3 指定扫描(需要关闭默认配置)
@ComponentScan(value = "com.hw.springannotation", useDefaultFilters = false,
        includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class})}
)       // 指定只扫描

3.3 注意

  • 如果是jdk8 ,@Repeatable(ComponentScans.class) 重复组件,可以多写几次
  • 如果不是,可以使用 @ComponentScans 指定多个扫描组件
@ComponentScans(value = {
        @ComponentScan(value = "com.hw.springannotation", useDefaultFilters = false,
                includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class})}
        ), @ComponentScan(value = "com.hw.springannotation",
        excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class, Service.class})})
})
原文地址:https://www.cnblogs.com/Grand-Jon/p/10018642.html