Spring bean instantiation by passing constructor args? [duplicate]

回眸只為那壹抹淺笑 提交于 2019-12-21 03:49:07

问题


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.

<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.

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

Now how can i pass the values to Employee2 constructor?

Thanks!


回答1:


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

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

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.



来源:https://stackoverflow.com/questions/21829162/spring-bean-instantiation-by-passing-constructor-args

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!