简体   繁体   English

基于Spring Boot构造函数的运行时依赖项注入

[英]Spring boot constructor based Runtime dependency injection

I have a Spring boot application in which I want Employee objects to be injected by Spring. 我有一个Spring引导应用程序,我希望Spring可以注入Employee对象。 There are two methods in which I pass different arguments to Employee constructor to get different objects in method1 and method2. 我通过两种方法将不同的参数传递给Employee构造函数,以在method1和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 像这样,我可能有一个methodn,其中我将不同的参数传递给构造函数并动态获取不同的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;
    }
}

In your configuration class, declare methods that return Employee and annotate them with @Bean . 在配置类中,声明返回Employee并用@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. 然后,在@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;   
    }
}

Then, in your classes you can just use @Autowired to retrieve either Employee 然后,在您的班级中,您可以只使用@Autowired来检索任一Employee

public class EmployeeRetrieval{

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

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

//your code here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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