正如问题所示,你如何 Autowire
以非 SpringBoot 托管类作为构造函数参数的类。
以下是说明这一点的代码块:
@Component
class Prototype
{
@Autowired
private Repository repository;
private NonSpringBootManagedBean bean;
Prototype(NonSpringBootManagedBean bean)
{
this.bean = bean;
}
}
@Component
class PrototypeClient
{
@Autowired
private ApplicationContext context;
private void createNewPrototype(NonSpringBootManagedBean bean)
{
// This throws an error saying no bean of type NonSpringBootManangedBean found
Prototype prototype = context.getBean(Prototype.class, bean);
}
}
我使用 ApplicationContext
的原因获取 Prototype
的实例而不是使用@Autowired
是因为我需要 Prototype
的新实例在方法内createNewPrototype()
每次调用它而不是单例实例时(另外,请告知这种获取新实例的方式是否不正确)。
更新:
正如其他人所说,将我对 bean 的创建移至 Java 配置类并添加由 @Bean
注释的方法。并实例化 NonSpringBootManagedBean
在 @Bean
方法。但我认为这是不可能的,因为这个 NonSpringBootManagedBean
由 PrototypeClient.createNewPrototype()
的调用者传递.
更新 我已经更清晰地更新了上面的代码示例。请立即引用此内容。
@Component
class Prototype
{
@Autowired
private Repository repository;
// Here Session is part of javx.websocket package and cannot be added as part of
// Java configuration class with a @Bean annotation
// In this case how can I use constructor injection?
private Session session;
Prototype(Session session)
{
this.session = session;
}
}
@Component
class PrototypeClient
{
@Autowired
private ApplicationContext context;
private void createNewPrototype(Session session)
{
Prototype prototype = context.getBean(Prototype.class, session);
}
}
@ServerEndpoint(value = "/resources")
class WebSocketController
{
private PrototypeClient client = ApplicationContext.getBean(PrototypeClient.class);
@OnMessage
void handleMessage(Session session, String message)
{
client.createNewPrototype(session);
}
}
最佳答案
您是否知道可以将 bean 范围更改为原型(prototype)引用而不是单例。这样您就可以将单个 bean 定义的范围限定为任意数量的对象实例。
https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html
private NonSpringBootManagedBean bean = new NonSpringBootManagedBean();
@Bean
public Prototype getPrototype(){
return new Prototype(bean);
}
关于java - 具有非 SpringBoot 托管构造函数参数的 Autowiring 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54904032/