【发布时间】:2018-09-08 02:31:46
【问题描述】:
我的应用程序使用自己的 Spring 配置 Condition 来根据设置提供 bean,但由于数量的原因,我希望将长 @Configuration 拆分而不是添加 @Conditional 到数十个 bean。
目前,我的主要安全配置如下所示
@Configuration @EnableOAuth2Client @EnableWebSecurity
@Import(OptionalAuthenticationConfiguration.class)
public class WebshopSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired(required = false)
private OptionalAuthenticationConfiguration auth;
这里是条件配置
@Configuration
@Conditional(MyCondition.class)
public class OptionalAuthenticationConfiguration {
[...]
由于@Conditional 的可选配置,@Import 注释失败
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webshopSecurityConfig': Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private OptionalAuthenticationConfiguration
WebshopSecurityConfig.auth; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [OptionalAuthenticationConfiguration] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
即使 bean 属性 WebshopSecurityConfig.auth 具有 required = false。
有没有办法在Spring中实现这种有条件的配置拆分?
【问题讨论】:
-
OptionalAuthenticationConfiguration是一个配置,你为什么要自动装配它?
标签: java spring configuration conditional