对于有关不同 bean 生命周期的问题,我找不到一个好的、简单的解决方案。
我想注入(inject)
@Resource
private Supplier<MessageHandler> messageHandlerFactory;
在每次调用 messageHandlerFactory.get();
时,在 @Service
bean 中创建一个新的 MessageHandler 实例(原型(prototype),具有自己的依赖项)。
我找到的解决方案名为 Method Injection对于这样一个常见的任务来说似乎过于复杂和麻烦。
使用 @Configuration
类最短、最简洁的解决方案是什么?
==更新==
最佳答案
您可以将 MessageHandler
的范围定义为 Prototype
:
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class MessageHandler {
}
并使用ObjectFactory
从单例中获取MessageHandler
。
@Component
public class YourSingleton {
@Autowired
ObjectFactory<MessageHandler> mhFactory;
public void doSomething() {
final MessageHandler messageHandler = mhFactory.getObject();
// messageHandler is a prototype
}
}
关于Spring - 简单地创建Supplier<MyPrototypeBean>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33021021/