Spring注解之@ComponentScan

@ComponentScan 其实就是起到了包扫描的作用。

传统方式的包扫描,是在配置文件中输入以下配置项:

<context:component-scan base-package="com.spring" use-default-filters="false"></context:component-scan>

 如果不用配置文件的方式,可以直接在类上添加@ComponentScan,起到的作用和上面一样,如下所示:

@ComponentScan 
public class MainConfig {
	
	//给容器中注册一个Bean;类型为返回值的类型,id默认是用方法名作为id
	@Bean("person")
	public Person person01(){
		return new Person("lisi", 20);
	}

}

@ComponentScan也可以指定自己需要扫描的组件,或者指定扫描时要排除的组件:

ComponentScan.Filter[] includeFilters() default {};

ComponentScan.Filter[] excludeFilters() default {};

以上两行代码是@ComponentScan中的源码,其实是两个拦截器,我们可以通过设置Value值来拦截不需要扫描的包,或者要排除的包,我们举一个includeFilters()的例子:


@ComponentScan(value = "com.springtest1",
        includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,
                classes = {Controller.class, Repository.class})},useDefaultFilters = false)
public class MainConfig {
    public Person person(){
        return new Person();
    }
}

通过以上设置,spring的容器中只会有@Controller和@Repository标注的类名。

注意以上代码中的type = FilterType.ANNOTATION代码,它的意思是根据注解来指定要扫描或者要排除的包。除此之外,还可以根据类名来指定要扫描或者要排除的包,这两个方式是最常用的,源码中还有其他的方法,如下所示:

package org.springframework.context.annotation;

public enum FilterType {
    ANNOTATION,
    ASSIGNABLE_TYPE,
    ASPECTJ,
    REGEX,
    CUSTOM;

    private FilterType() {
    }
}

所以在学习时,要看看底层的代码,这样我们就可以了解更多的知识。关于@ComponentScan呢,其实还要讲的是,jdk1.8支持多个@ComponentScan在同一个类上多次注解,jdk1.8以下就需要使用另外一个@ComponentScans注解了,大家自己去发现@ComponentScans注解吧。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值