好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

springboot 启动如何排除某些bean的注入

springboot 启动排除某些bean的注入

问题:

最近做项目的时候,需要引入其他的jar。然后还需要扫描这些jar里的某些bean。于是使用注解:@ComponentScan

这个注解直接指定包名就可以,它会去扫描这个包下所有的class,然后判断是否解析:

?

1

2

3

@ComponentScan (basePackages = { "your.pkg" , "other.pkg" })

public class Application {

} 

其他的jar中定义了 redissonConfig 这个bean。然后我自己的项目也定义了redissonConfig 这个bean。导致项目启动报错。所以使用如下方式,排除jar 中的RedissonConfig.class。

?

1

@ComponentScan (basePackages = { "com.xx.xx.*" }, excludeFilters = @ComponentScan .Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {RedissonConfig. class }))

@ComponentScan注解

扫描或解析的bean只能是Spring内部所定义的,比如@Component、@Service、@Controller或@Repository。如果有一些自定义的注解,比如@Consumer、这个注解修饰的类是不会被扫描到的。这个时候我们就得自定义扫描器完成这个操作。

配置文件中使用的:

component-scan标签底层使用ClassPathBeanDefinitionScanner这个类完成扫描工作的。@ComponentScan注解配合@Configuration注解使用,底层使用ComponentScanAnnotationParser解析器完成解析工作。

springboot排除扫描包

?

1

2

3

4

5

6

7

8

9

10

11

@SpringBootApplication

@ComponentScan (excludeFilters =

  {

    @ComponentScan .Filter(type = FilterType.REGEX,pattern = "com.action.other.*" )

  })

public class Application {

 

     public static void main(String[] args) {

         SpringApplication.run(Application. class , args);

     }

}

根据FilterType不同有不同的过滤方式,这里是根据正则过滤

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://HdhCmsTestcnblogs测试数据/hui-run/p/9800366.html

查看更多关于springboot 启动如何排除某些bean的注入的详细内容...

  阅读:31次