基于Spring Run构造函数的Runtime依赖注入

时间:2018-02-18 07:28:28

标签: java spring-boot

我有一个Spring启动应用程序,我希望Spring注入Employee对象。有两种方法可以将不同的参数传递给Employee构造函数,以获取method1和method2中的不同对象。像这样我可能有方法,我将不同的参数传递给构造函数并动态获取不同的Employee对象。如何使用Autowired注释而不使用xml配置

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;
    }
}

1 个答案:

答案 0 :(得分:2)

在配置类中,声明返回Employee的方法,并使用@Bean注释它们。然后,在@Service中,您可以使用@Autowired@Qualifier注入bean,其中限定符名称是用于定义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;   
    }
}

然后,在您的课程中,您只需使用@Autowired来检索Employee

public class EmployeeRetrieval{

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

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

//your code here
}