如何配置@ComponentScan动态?

@ComponentScan( //CS1 basePackages = {"com.package.A", "com.package.B"}, excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = {com.Package.A.SomeClass.class }) ) @ComponentScan( //CS2 basePackages = { "com.package.A"} ) @EnableAutoConfiguration @SpringBootApplication public class Application { public static void main(String[] args) throws Exception { ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args); } } 

上面是我的SpringBootApplication的主类。 如您所见,我必须使用Annnotation,而不是xml 。 有两个@ComponentScan Annotations.And当然不允许使用它。 对我来说,两个不同的@ComponentScan意味着启动我的应用程序的两种不同方式。 如果我选择使用CS1(意思是@ ComponentScan1),我就会评论CS2,反之亦然。

它不优雅或优雅。特别适合那些为spring新手。 所以我想知道如何根据我的.properties文件将其配置为动态 。例如我的.properties文件中名为“isScanA”的param是真的,那么我可以使用CS1。 或任何其他优雅的方式。

我已经尝试了很多。

  1. 使用占位符。 例如@ComponentScan(basePackage="${scan.basePackage}") 。并在需要时更改.properties文件中的值。 但这种方式无法修复excludeFilters 。 因为如果我使用FilterType.ASSIGNABLE_TYPE来分配需要排除的类,则该value应该是Class类型而不是String ,其中如果使用value = {"${scan.excludeClass}"}

  2. 程序化方式。

     /** * Create a new AnnotationConfigApplicationContext, scanning for bean definitions * in the given packages and automatically refreshing the context. * @param basePackages the packages to check for annotated classes */ public AnnotationConfigApplicationContext(String... basePackages) { this(); scan(basePackages); refresh(); } 

我在我的main函数中调用了这个方法。但它也无法修复excludeFilters问题,原因在于: 做上下文:组件扫描编程方式?

我真的尝试了很多,但仍然无法解决。 所以我需要你的帮助。

请原谅我可怜的英语,PLZ。

Thanx很多,至少你花了一点时间阅读。

也许你正在寻找Spring的简介! Spring Profile允许您确定配置和Bean的配置文件。 我认为你必须将配置类分开才能拥有两个配置文件! 看看那些例子吧!

这是文档:

http://docs.spring.io/autorepo/docs/spring-boot/current/reference/html/boot-features-profiles.html