简体   繁体   中英

Passing values to spring bean programmatically?

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!

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM