gno*_*nos 10 java spring spring-boot
我想要一个spring bean 在另一个bean之后进行实例化.所以我只是使用@DependsOn注释.
问题是:这个其他bean是一个带有@ConditionalOnProperty(name = "some.property", havingValue = "true")注释的条件bean
.因此,当属性为false时,bean不会被实例化(这就是我们想要的),并且@DependsOn显然会失败.这里的目标是:无论如何创建第二个bean,但是如果它被创建,则在第一个bean之后创建它.
有没有办法做到这一点,而不删除@ConditionalOnProperty?并且没有玩@Order注释?
谢谢您的帮助
如何使用以下方法:
interface Something {}
public class FirstBean implements Something {}
public class SecondBean implements Something{} // maybe empty implementation
Run Code Online (Sandbox Code Playgroud)
现在配置如下:
@Configuration
public class MyConfiguration {
@Bean(name = "hello")
@ConditionalOnProperty(name = "some.property", havingValue = true)
public Something helloBean() {
return new FirstBean();
}
@Bean(name = "hello")
@ConditionalOnProperty(name = "some.property", havingValue = false)
public Something secondBean() {
return new SecondBean();
}
@Bean
@DependsOn("hello")
public MyDependantBean dependantBean() {
return new MyDependantBean();
}
}
Run Code Online (Sandbox Code Playgroud)
这个想法是无论如何都要创建“ Something” bean(即使它是一个空的实现),以便在任何情况下依赖bean都将依赖于Something。
我自己还没有尝试过,春天充满魔力,但也许值得一试:)
@DependsOn您可以使用which来代替使用@AutoConfigureAfter(),即使第一个 bean 没有创建,也可以创建第二个 bean,但仍然保持顺序。
@Configuration
public class FirstConfiguration {
@Bean(name = "firstBean")
@ConditionalOnProperty(name = "some.property", havingValue = true)
public FirstBean firstBean() {
return new FirstBean();
}
}
@Configuration
@AutoConfigureAfter(name = {"firstBean"})
public class SecondConfiguration {
@Bean
public SecondBean secondBean() {
return new SecondBean();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用自定义条件类:
public class BeanPresennceCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
FirstBean firstBean = null;
try {
firstBean = (FirstBean)context.getBeanFactory().getBean("firstBean");
}catch(NoSuchBeanDefinitionException ex) {
}
return firstBean != null;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2903 次 |
| 最近记录: |