大佬教程收集整理的这篇文章主要介绍了spring – 包装上的条件ComponentScan,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
在Spring Boot应用程序中,我有一个包含Application类的包
@SpringBootApplication
class Application {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(Application);
application.run(args);
}
}
默认情况下,它会自动从该类的包中设置ComponentScan.然后我有几个子包,每个子包包含几个组件和服务bean(使用注释).但是为了针对不同的用例重用此应用程序,我需要启用/禁用某些子包中的所有组件,最好是通过属性.
那就是我喜欢的子包
org.example.app.provider.provider1
org.example.app.provider.provider2
现在,基于某些属性,我想在其中一个软件包中启用(扫描)bean,例如
provider1.enabled=true
我以为我可以使Configuration类上的ConditionalOnProperty像这样工作,但问题是,默认的@SpringBootApplication组件扫描会拾取bean(即子包配置类不会覆盖顶级组)
使用@ConditionalOnProperty注释的Spring配置就是这样做的:
@Configuration
@ComponentScan("org.example.app.provider.provider1")
@ConditionalOnProperty(name = "provider1.enabled",havingValue = "true")
public class Provider1Configuration {
}
@Configuration
@ComponentScan("org.example.app.provider.provider2")
@ConditionalOnProperty(name = "provider2.enabled",havingValue = "true")
public class Provider2Configuration {
}
然后排除org.example.app.provider下的组件.*
现在,您只需要从Spring Boot Application中排除提供程序(并让CondtionalOnProperty完成它的工作).你可以:
>(1)移动提供程序包,使它们不低于Spring Boot应用程序
例如,如果Spring Boot main位于org.example.app中,请将orCon.example.app中的@Configuration保留在org.example.providers中的提供程序中.
>(2)或者从Spring Boot中排除提供程序包(假设@Configuration位于org.example.app中):
SpringBootMain.java:
@SpringBootApplication
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASPECTJ,pattern = "org.example.app.provider.*"))
class Application {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(Application);
application.run(args);
}
}
以上是大佬教程为你收集整理的spring – 包装上的条件ComponentScan全部内容,希望文章能够帮你解决spring – 包装上的条件ComponentScan所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。