Passing values to spring bean programmatically?

2020-04-18 06:40发布

问题:

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.

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

Now how can i pass the values to Employee2 constructor?

Thanks!

回答1:

When you do the bean lookup. Use the varargs getBean method instead to send in arguments to the constructor.

So try something like this:

Employee2 emp = (Employee2)applicationContext.getBean("emp2", "someid", "somename", "somesalaray");