Spring之@ComponentScan注解

在配置类中:

@Configuration //告诉spring这是个配置类
//扫描com.spring包下的@Service、@Controller、@Repository、@Component (interface文件加了注解注入不进去)
//也可定义过滤
@ComponentScan(value = "com.spring",excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class, Service.class})
})
public class SpringConfig {

    /**
     * 给spring ioc中注册一个bean,返回值为类型,方法名为id
     * 将返回值注入到容器中,方法名为组件id
     */
    @Bean
    public Person personTest(){
        return new Person("小陈","22");
    }
}

在xml文件中

    <context:component-scan base-package="com.spring"></context:component-scan>

main方法测试
在这里插入图片描述
扩展:

@ComponentScan(value = "com.spring",excludeFilters = {
 		//根据注解扫描过滤
       /* @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class, Service.class}),*/
        //根据给定类型过滤
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,classes = {PersonService.class})
})
public class SpringConfig {

    /**
     * 给spring ioc中注册一个bean,返回值为类型,方法名为id
     * 将返回值注入到容器中,方法名为组件id
     */
    @Bean
    public Person personTest(){
        return new Person("小陈","22");
    }
}

自定义注解扫描过滤:

@Configuration //告诉spring这是个配置类
//扫描com.spring包下的@Service、@Controller、@Repository、@Component (interface文件加了注解注入不进去)
//也可定义过滤
@ComponentScan(value = "com.spring",excludeFilters = {
        //根据注解扫描过滤
       /* @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class, Service.class}),*/
        //根据给定类型过滤
        /*@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,classes = {PersonService.class}),*/
        //自定义注解
        @ComponentScan.Filter(type = FilterType.CUSTOM,classes = {MyComponentFilter.class})
})
public class SpringConfig {

    /**
     * 给spring ioc中注册一个bean,返回值为类型,方法名为id
     * 将返回值注入到容器中,方法名为组件id
     */
    @Bean
    public Person personTest(){
        return new Person("小陈","22");
    }
}

自己写个过滤类:

public class MyComponentFilter implements TypeFilter {
    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {

        AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();

        ClassMetadata classMetadata = metadataReader.getClassMetadata();

        Resource resource = metadataReader.getResource();

        String className = classMetadata.getClassName();
        System.out.println("类名称:"+className);
        //定义过滤规则,如果组件id名称中包含字母ce的过滤掉
        if (className.contains("ce")){
            return true;
        }
        return false;
    }
}

main方法测试:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值