Spring - 只需创建供应商<MyPrototypeBean>
Spring - Simply create Supplier<MyPrototypeBean>
对于不同 bean 生命周期的问题,我找不到好的简单解决方案。
我想注射一个
@Resource
private Supplier<MessageHandler> messageHandlerFactory;
在我每次调用 messageHandlerFactory.get();
.
时在 @Service
bean 中创建一个新的 MessageHandler 实例(原型,具有自己的依赖项)
我找到的名为 Method Injection 的解决方案对于这样一个常见任务来说似乎过于复杂和繁琐。
使用 @Configuration
class 的最短和最干净的解决方案是什么?
==更新==
您可以将 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
}
}
对于不同 bean 生命周期的问题,我找不到好的简单解决方案。
我想注射一个
@Resource
private Supplier<MessageHandler> messageHandlerFactory;
在我每次调用 messageHandlerFactory.get();
.
@Service
bean 中创建一个新的 MessageHandler 实例(原型,具有自己的依赖项)
我找到的名为 Method Injection 的解决方案对于这样一个常见任务来说似乎过于复杂和繁琐。
使用 @Configuration
class 的最短和最干净的解决方案是什么?
==更新==
您可以将 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
}
}