@ComponentScan-自动扫描组件&指定扫描规则

1,@ComponentScan注解是什么

其实很简单,@ComponentScan主要就是定义扫描的路径从中找出标识了需要装配的类自动装配到spring的bean容器中

2,@ComponentScan注解的详细使用

做过web开发的同学一定都有用过@Controller,@Service,@Repository注解,查看其源码你会发现,他们中有一个共同的注解@Component,没错@ComponentScan注解默认就会装配标识了@Controller,@Service,@Repository,@Component注解的类到spring容器中,好下面咱们就先来简单演示一下这个例子

示例:

创建controller:

@Controller
public class UserController {
}

创建service:

@Service
public class UserService {
}

创建dao:

@Repository
public class UserDao {
}

添加启动类:

@Configuration
@ComponentScan(value = "com.spring.annotation")
public class ScanConfig {

}

设置@ComponentScan注解,添加 value = "com.spring.annotation" ,表示扫描对应包下的所有注解

测试:

    @Test
    public void test02() {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScanConfig.class);
        String[] beanDefinitionNames = context.getBeanDefinitionNames();
        for (String name : beanDefinitionNames) {
            System.out.println(name);
        }
    }

结果:

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory

scanConfig
annotationConfig
userController
userDao
userService

可以看到对应的实体类已经注入到容器中

不仅如此,@ComponentScan 提供了过滤器可以过滤指定的注解进行注入

excludeFilters (排除过滤器)

@Configuration
@ComponentScan(value = "com.spring.annotation",excludeFilters = {
        @ComponentScan.Filter(type=FilterType.ANNOTATION,classes={Controller.class})
})
public class ScanConfig{

}

 @ComponentScan.Filter 指定了过滤器的规则,FilterType.ANNOTATION 表示按注解过滤(其他几种方法稍后再讲),classes指定需要过滤的注解,Controller注解被排除,classes为数组可以指定多个,重新运行结果:

scanConfig
annotationConfig
userDao
userService

可以看到 原来的 userController 已经消失,说明没有被注入到容器中去


includeFilters  (包含过滤器)

@Configuration
@ComponentScan(value="com.spring.annotation",
//        excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class})}
        includeFilters = {
            @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class}
        )},useDefaultFilters = false
)
public class ScanConfig {
}

运行结果:

scanConfig
userController

可以看到只有 被@controller注解的bean注入到容器中去

 

 

 

 

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值