我需要创建一个spring bean的多个实例(我们称之为MainPrototypeBean
),我可以使用prototype
作用域。它依赖于其他一些bean,并且我想在每次创建主bean时创建它们的新实例。但是,一些bean之间存在共享依赖关系,我们称之为SharedPrototypeBean
。如何在每个依赖bean中注入相同的SharedPrototypeBean
实例,同时为每个MainPrototypeBean
创建一个新实例?在春天共享原型豆
我正在考虑实现一个自定义范围,但我希望找到一个更清洁的方式。制作任何bean singletons不是一种选择,因为它们需要在MainPrototypeBean
的不同实例之间隔离。
这里是什么,我试图做一个例子:
@SpringBootApplication
public class DIDemo {
public static void main(String[]args){
ConfigurableApplicationContext context = SpringApplication.run(DIDemo.class, args);
context.getBean(MainPrototypeBean.class);
}
@Component @Scope("prototype") static class SharedPrototypeBean {}
@Component @Scope("prototype") static class FirstPrototypeBean {
@Autowired SharedPrototypeBean shared;
@PostConstruct public void init() {
System.out.println("FirstPrototypeBean.init() with shared " + shared);
}
}
@Component @Scope("prototype") static class SecondPrototypeBean {
@Autowired SharedPrototypeBean shared;
@PostConstruct public void init() {
System.out.println("SecondPrototypeBean.init() with shared " + shared);
}
}
@Component @Scope("prototype") static class MainPrototypeBean {
@Autowired FirstPrototypeBean first;
@Autowired SecondPrototypeBean second;
}
}
和执行它的输出:
FirstPrototypeBean.init() with shared [email protected]
SecondPrototypeBean.init() with shared [email protected]
原型bean对容器制作的每次注入都有不同的实例。我认为'SharedPrototypeBean'实际上不是原型范围的bean,而是'@Scope(“singleton”)'。 –
@ M.Prokhorov,但是这并不意味着所有的'MainPrototypeBean'实例都会使用相同的'SharedPrototypeBean',因此玷污了必要条件? – Mena
注意:我怀疑使用范围代理可能有帮助。 – Mena