Java 通过传递构造函数args来实例化Spring bean?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21829162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:56:55  来源:igfitidea点击:

Spring bean instantiation by passing constructor args?

javaspringspring-mvcspring-3

提问by user755806

I have below spring bean.

我有下面的春豆。

public class Employee2 {

  private int id;
  private String name;
  private double salary;


  public Employee2(int id, String name, double salary) {
    this.id = id;
    this.name = name;
    this.salary = salary;
  }

 // some logic to call database using above values

}

Now i have below config in spring configuration file.

现在我在 spring 配置文件中有以下配置。

<bean id="emp2" class="com.basic.Employee2">
            <constructor-arg name="id" value="" />
            <constructor-arg name="name" value="" />
            <constructor-arg name="salary" value="" />
</bean>

Now i cannot hard code the values in above config since they are dynamic.

现在我不能硬编码上面配置中的值,因为它们是动态的。

Now i am getting spring bean programmatically using below code. The bean scope is singelton.

现在我使用下面的代码以编程方式获取 spring bean。bean 范围是 singelton

Employee2 emp = (Employee2)applicationContext.getBean("emp2");

Now how can i pass the values to Employee2 constructor?

现在如何将值传递给 Employee2 构造函数

Thanks!

谢谢!

回答by Konstantin Yovkov

You can use the ApplicationContext#getBean(String name, Object ... params)method, which

您可以使用ApplicationContext#getBean(String name, Object ... params)方法,该方法

Allows for specifying explicit constructor arguments / factory method arguments, overriding the specified default arguments (if any) in the bean definition.

允许指定显式构造函数参数/工厂方法参数,覆盖 bean 定义中指定的默认参数(如果有)。

For example:

例如:

Integer param1 = 2;
String param2 = "test";
Double param3 = 3.4;
Employee2 emp = 
          (Employee2)applicationContext.getBean("emp2", param1, param2, param3);

Anyway, while this will possibly work, you should consider using Spring EL, as noted in one of the comments under the question.

无论如何,虽然这可能会奏效,但您应该考虑使用Spring EL,如问题下的评论之一所述。