【问题标题】:Is there a way you can inject a class whose constructor has parameters in micronaut?有没有办法可以注入一个类,其构造函数在 micronaut 中有参数?
【发布时间】:2019-11-23 11:27:07
【问题描述】:

假设我有 A 类。

class A {
    private String s;

    public A(String s) {
        this.s = s;
    }
}

我想将 A 注入到 B 类中。

到目前为止,我一直在注入没有构造函数参数的类,例如

class B {

    @Inject
    private A a;
}

但我不知道如何注入带有构造函数参数的类。 我该怎么做?

【问题讨论】:

  • 你的意思是class B{ private A a; },你在找什么注射之王?

标签: java micronaut


【解决方案1】:

我认为在您的示例中 A 将是一个原型 bean,因为它有一个您必须提供的参数。因为您必须提供参数,所以不能像单例一样简单地注入 bean。您可以注入BeanContext 并调用createBean。例如:beanContext.createBean(A.class, "some string value")。这将需要使用 @Prototype 注释 A 以及应由创建者提供的任何构造函数参数 @Parameter

【讨论】:

    【解决方案2】:

    而不是这个:

    @Singleton
    class B {
        @Inject
        private A a;
    }
    

    你可以这样:

    @Singleton
    class B {
    
        private A a;
    
        public B(A a) {
            this.a = a;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-09-28
      • 2012-11-26
      • 2014-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      • 1970-01-01
      • 2019-03-01
      相关资源
      最近更新 更多