gpt4 book ai didi

java - Spring多个配置相同接口(interface)的bean

转载 作者:太空宇宙 更新时间:2023-11-04 12:08:09 27 4
gpt4 key购买 nike

如何通过 @Configuration 类返回任意数量的相同类型的 @Bean 对象?像这样的东西:

@Configuration
public class MyClass {
@Bean
public MyBean myBean {
for (String myBeanName: getMyBeanNames()) {
MyBean myBean = new MyBean();
myBean.setName(myBeanName);
return myBean
}
}

显然该代码片段无法编译,但我如何实现结果?

最佳答案

我最终这样做了:

 @PostConstruct
public void postConstruct() {
ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
for (String myBeanName: getMyBeanNames()) {
MyBean myBean = new MyBean();
myBean.setName(myBeanName);
beanFactory.registerSingleton(myBean.class.getName() + myBean.getName(), myBean)
}
}

关于java - Spring多个配置相同接口(interface)的bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40136276/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com