Raghu
Raghu

Reputation: 43

Spring boot constructor based Runtime dependency injection

I have a Spring boot application in which I want Employee objects to be injected by Spring. There are two methods in which I pass different arguments to Employee constructor to get different objects in method1 and method2. Like this I may have methodn in which I pass different arguments to constructor and get different Employee objects dynamically.How do I do it using Autowired annotation without using xml configuration

package com.test;


public class EmployeeCreation{

    public Employee method1(){
        Address add1 = new Address("street1", "street2");
        Employee e1 = new Employee("emp1", add1);
        return e1;
    }

    public Employee method2(){
        Address add2 = new Address("street3", "street4");
        Employee e2 = new Employee("emp2", add2);
        return e2;
    }

}



class Employee {

    private String name;
    private Address address;
    public Employee(String name, Address address) {
        this.name = name;
        this.address = address;
    }

}

class Address {
    private String street1;
    private String street2;
    public Address(String street1, String street2) {
        this.street1 = street1;
        this.street2 = street2;
    }
}

Upvotes: 0

Views: 1193

Answers (1)

Yserbius
Yserbius

Reputation: 1414

In your configuration class, declare methods that return Employee and annotate them with @Bean. Then, in your @Service you can inject the beans using @Autowired and @Qualifier where the qualifier name is the name of the configuration method used to define the bean.

@Configuration
public class AppConfig{

    @Bean
    public Employee employee1(){
        Address add1 = new Address("street1", "street2");
        Employee e1 = new Employee("emp1", add1);
        return e1;   
    }
    @Bean
    public Employee employee2(){
        Address add2 = new Address("street2", "street3");
        Employee e2 = new Employee("emp2", add2);
        return e2;   
    }
}

Then, in your classes you can just use @Autowired to retrieve either Employee

public class EmployeeRetrieval{

@Autowired
@Qualifier("employee1")
private Employee emp1;

@Autowired
@Qualifier("employee1")
private Employee emp1;

//your code here
}

Upvotes: 2

Related Questions