Springboot之@ComponentScan

@ComponentScan的源码

排除过滤器条件的Bean

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

满足过滤器条件的Bean才去扫描

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

过滤器@ComponentScan.Filter

默认的FilterType 是 FilterType.ANNOTATION 按照注解方式
其余的几种分别是:

  • FilterType.ASSIGNABLE_TYPE 按照给定的类型
  • FilterType.ASPECTJ 按照ASPECTJ表达式
  • FilterType.REGEX 按照正则表达
  • FilterType.CUSTOM 按照自定义规则
  public @interface Filter {
        FilterType type() default FilterType.ANNOTATION;

        @AliasFor("classes")
        Class<?>[] value() default {};

        @AliasFor("value")
        Class<?>[] classes() default {};

        String[] pattern() default {};
    }

定义要扫描的包

   @AliasFor("basePackages")
    String[] value() default {};
   @AliasFor("value")
    String[] basePackages() default {};

定义要扫描的类

 Class<?>[] basePackageClasses() default {};

扫描指定对应的包排除指定对应的包

@Configuration
@ComponentScan(basePackages = {"com.example.demo.chapter4"},excludeFilters={@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Service.class)})
public class AppConfig {
//
//    @Bean("user")
//    public User inituser(){
//
//        User user=new User();
//        user.setUsername("小明");
//        user.setId(1L);
//        user.setNote("你好啊");
//        return user;
//    }
}

获取Bean

ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
        User user=(User) ctx.getBean(User.class);
        UserService userService=ctx.getBean(UserService.class);
        logger.info(user.getUsername());
        userService.printUser(user);

运行结果:
由于加入了excludeFilters配置,标注@Service的类不再被Ioc容器扫描注入

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.chapter4.UserService' available

User

@Component("userId")
public class User {

    @Value("1")
    private Long id;
    @Value("张三")
    private  String username;

    @Value("李四是张三的爸爸")
    private String note;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }
}

UserService 类

@Service
public class UserService {

    public  void printUser(User user){
        System.out.println("编号"+user.getId()+user.getNote());
    }
}

你可能感兴趣的:(Springboot之@ComponentScan)