问题
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