以编程方式将值传递给spring bean? [英] Passing values to spring bean programmatically?
本文介绍了以编程方式将值传递给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
}
现在我在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。
Now i am getting spring bean programmatically using below code.
Employee2 emp = (Employee2)applicationContext.getBean("emp2");
现在如何将值传递给Employee2构造函数?
谢谢!
推荐答案
进行bean查找时。使用varargs getBean方法代替将参数发送给构造函数。
When you do the bean lookup. Use the varargs getBean method instead to send in arguments to the constructor.
所以尝试这样的事情:
Employee2 emp = (Employee2)applicationContext.getBean("emp2", "someid", "somename", "somesalaray");
这篇关于以编程方式将值传递给spring bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文