Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring bean instantiation by passing constructor args? [duplicate]

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!

like image 201
user755806 Avatar asked Feb 17 '14 12:02

user755806


1 Answers

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.

like image 139
Konstantin Yovkov Avatar answered Nov 04 '22 07:11

Konstantin Yovkov