Spring bean实例化通过传递构造函数args? [英] Spring bean instantiation by passing constructor args?
问题描述
我有春天豆。
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
}
现在我在spring配置文件中有以下配置。
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.
现在我使用下面的代码以编程方式获取spring bean。 bean范围是singelton 。
Now i am getting spring bean programmatically using below code. The bean scope is singelton.
Employee2 emp = (Employee2)applicationContext.getBean("emp2");
现在如何将值传递给Employee2构造函数?
谢谢!
推荐答案
您可以使用 ApplicationContext#getBean(String name,Object ... params)方法,
允许指定显式构造函数参数/ factory方法
参数,覆盖
bean定义中指定的默认参数(如果有)。
Allows for specifying explicit constructor arguments / factory method arguments, overriding the specified default arguments (if any) in the bean definition.
For例如:
Integer param1 = 2;
String param2 = "test";
Double param3 = 3.4;
Employee2 emp =
(Employee2)applicationContext.getBean("emp2", param1, param2, param3);
无论如何,虽然这可行,但你应该考虑使用 Spring EL ,如该问题的其中一条评论所述。
Anyway, while this will possibly work, you should consider using Spring EL, as noted in one of the comments under the question.
这篇关于Spring bean实例化通过传递构造函数args?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!