【问题标题】:java injection - how to inject a bean with parametrized constructorjava注入-如何使用参数化构造函数注入bean
【发布时间】:2016-11-26 12:01:31
【问题描述】:

我想使用@inject 来注入一个具有参数化构造函数的bean。在注入时,我需要将参数传递给 bean。解释清楚。

A 类:

public class A{
  private String name;
  private String id;
  private int age;

  public A(Student student){
    name = student.getName();
    id = student.getId();
    age = student.getAge();
  }

  public String getName(){
     return Name;
  }

  ..

  ..

}

必须注入 A 类 bean 的 B 类:

public class B{

  @inject private Student student;

  //how to inject the below passing student value
  @inject private A a; // new A(student);

  public getNameAndAge(){
      String name = a.getName();
      int age = a.getAge();
      System.out.println(name);
  }

  public sendDetails(){
     sendInWebService(a);
  }

  ..
  ..

}

在 B 类中,bean A 必须在许多方法中本地使用。希望这段代码 sn-ps 有助于理解我的问题。我是 Spring 和 Java 依赖注入的新手。我们的应用程序没有 Spring 依赖项,因此 @inject 是执行此操作的唯一选择。

提前致谢。

【问题讨论】:

  • 您的 A 似乎是域 POJO,制作 Spring 管理的对象没有任何好处。为什么不通过new 实例化它?

标签: spring jakarta-ee dependency-injection autowired inject


【解决方案1】:

看看这个线程。 java - Pass Parameter to Instance of @Inject Bean - Stack Overflow

它会通过适当的解释来处理您的问题。

【讨论】:

    猜你喜欢
    • 2011-05-11
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 2018-03-27
    相关资源
    最近更新 更多