Spring 使用构造方法注入方式
4.3以后只有一个构造方法的话,属性不需要使用@Autowired
修饰
@Component
class Cake {
private Flavor flavor;
Cake(Flavor flavor) {
Objects.requireNonNull(flavor);
this.flavor = flavor;
}
Flavor getFlavor() {
return flavor;
}
...
}
如果有多个构造方式 ,则需要使用@Autowired
告诉spring使用哪个方法注入
@Component
class Sandwich {
private Topping toppings;
private Bread breadType;
Sandwich(Topping toppings) {
this.toppings = toppings;
}
@Autowired
Sandwich(Topping toppings, Bread breadType) {
this.toppings = toppings;
this.breadType = breadType;
}
...
}