java - 具有非 SpringBoot 托管构造函数参数的 Autowiring 类

标签 java spring-boot

正如问题所示,你如何 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方法。但我认为这是不可能的,因为这个 NonSpringBootManagedBeanPrototypeClient.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/

相关文章:

java - 如何在 spring-boot 应用程序中正确配置更多身份验证提供程序

spring-boot - 用于安全托管 zip 文件的 Azure 服务

java - 如何用正则表达式删除第二个子字符串?

java - 从Java中的匿名对象访问非静态对象

java - 从 JNI 调用 Java 方法

spring-boot - 无法使用 Spring Cloud 连接 AWS SES

java - 低于 17 的 API 的 Android AlertDialog setOnDismissListener

java - 内部类使用外部类的方法。那是循环引用吗?如何避免

spring - Zuul代理动态发现路由

java - 为什么 Spring Batch 从 MASTER 读取元数据表而不是从用户定义的架构中读取元数据表?