Spring 使用构造方法注入方式

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

原博客地址:https://reflectoring.io/constructor-injection/

posted @ 2021-05-07 19:27  cheakceep  阅读(385)  评论(0编辑  收藏  举报