@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
注解。当然,Spring 不允许这样做。对我来说,两者不同@ComponentScan
意味着启动我的应用程序的两种不同方式。如果我选择使用CS1(这意味着@ComponentScan1),我必须评论CS2,反之亦然。
它不优雅或优美。特别是对于那些 Spring 新手。所以我想知道如何根据我的 .properties 文件动态配置它。这样由于我的 .properties 文件中名为“isScanA”的参数为 true,那么我可以使用 CS1。或者任何其他优雅的方式。
我已经尝试了很多。
使用占位符。如
@ComponentScan(basePackage="${scan.basePackage}")
并在需要时更改 .properties 文件中的值。但这种方式无法修复excludeFilters
。因为如果我使用FilterType.ASSIGNABLE_TYPE
要分配需要排除的类,value
应该是Class
输入不是String
,如果value = {"${scan.excludeClass}"}
被使用。编程方式。
/** * 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(); }
我在主函数中调用了这个方法。但它也无法修复excludeFilters
问题,原因在这里:Doing context:component-scan programatic way?
...
我真的尝试了很多,但还是无法解决。所以我需要你的帮助。
请原谅我糟糕的英语。
非常感谢,至少你花了一点时间阅读。
最佳答案
也许您正在寻找 Spring 的个人资料! Spring Profile 允许您确定配置和 Bean 的配置文件。我认为你必须将配置类分开才能有两个配置文件!看看这些例子!
这是文档:
http://docs.spring.io/autorepo/docs/spring-boot/current/reference/html/boot-features-profiles.html
关于java - 如何动态配置@ComponentScan?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40359838/