spring @Autowired 使用的4种场景

  1. 有参构造函数,效率高。
    @Autowired
    public CDPlayer(CompactDisc cd, Power power) {
        this.cd = cd;
        this.power = power;
        System.out.println("CDPlayer多参构造函数");
    }
  1. 成员变量,利用反射,效率低。
	@Autowired
    private Power power;
  1. setter 方法
	private CompactDisc cd;
	
	@Autowired
    public void setCd(CompactDisc cd) {
        this.cd = cd;
        System.out.println("调用 setCd");
    }
  1. 用在任意一个方法上
    private CompactDisc cd;

    private Power power;
    
	@Autowired
    public void prepare(CompactDisc cd, Power power){
        this.cd = cd;
        this.power = power;
        System.out.println("调用prepare");
    }

你可能感兴趣的:(Spring)