Spring:基于Constructor多态的Autowire

时间:2018-03-27 08:13:52

标签: java spring spring-boot dependency-injection autowired

我有Component类Customer,如:

class Customer{
    private String firstName;
    private String lastName;

    public Customer() {
        firstName = "dummy";
        lastName = "dummy";
    }

    public Customer(String first, String last) {
        firstName = first;
        lastName = last;
    }

}

我想将Customer实例自动装配到以下类

class MainDefault{

    // Should autowire object with default Customer Constructor
    @Autowire
    private Customer customer;

    public void doWork() {
        System.out.println(customer.firstName);
    }

}

class Mainparameterized{

    // Should autowire object with parameterized Customer Constructor
    @Autowire
    private Customer customer;

    public void doWork() {
        System.out.println(customer.firstName);
    }
}

这里MainDefault应该使用默认构造函数,Mainparameterized应该使用参数化构造函数。

最好的方法是什么。?

0 个答案:

没有答案