[英]How to create a conditional bean in Spring
我需要在 Spring 中创建一个Conditional
Bean。 用例如下:
Class 1
在这个 class 中,我们正在尝试创建Bean
,它应该为一些具有所需权限的客户端创建,而对于其他客户端,它将返回empty()
。 因此,应用程序应该在没有BeanCreationException
的情况下为所有客户端启动
@org.springframework.context.annotation.Configuration
public class SomeBeanConfiguration {
@Bean
public Optional<SomeBean> someBean() {
// whoAmI() ? returns IAmClient_1 - for whom this bean should be created
// whoAmI() ? returns IAmClient_2 - for whom this bean should not be created
final String somePermission = whoAmI();
try {
return Optional.of(SomeBean.builder()
.withPermission(new SomeCredentialsProvider(somePermission))
.build());
} catch (Exception ex) {
LOG.error("SomeBean creation exception : ", ex);
}
return Optional.empty();
}
}
Class 2我们在构造函数注入中使用这个 Bean
@Bean
public SomeHelper someHelper(Optional<SomeBean> someBean) {
return new someHelper(someBean);
}
但是具有权限的客户端的someHelper
也在构造函数中获得了Optional.empty()
。
我在这里做错了什么? 有人可以帮忙吗?
您需要更改创建 bean 的方法。 它不应该返回Optional
类型的 bean,而应该返回SomeBean
类型的 bean。 此外,考虑将您的逻辑重写为更易于理解的内容,例如删除 catch 块并基于whoAmI()
的 output 创建 bean。
@Bean
public SomeBean someBean() {
// whoAmI() ? returns IAmClient_1 - for whom this bean should be created
// whoAmI() ? returns IAmClient_2 - for whom this bean should not be created
String somePermission = whoAmI();
if (somePermission.equals("IAmClient_1") {
return SomeBean.builder().withPermission(newSomeCredentialsProvider(somePermission)).build());
} else {
return null;
}
}
现在,当您自动装配 Optional 时,该 optional 将包含IAmClient_1
的 bean,并且对于所有其他情况都是空的。
在我看来,最好始终构造SomeBean
并根据您正在检查的权限的值修改其行为,但这取决于您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.