Spring引导中的构造函数是否必须使用@Autowired注释

时间:2018-04-18 07:10:17

标签: spring-boot dependency-injection autowired

如果我使用构造函数DI,是否必须放置@Autowired

1 个答案:

答案 0 :(得分:4)

  

构造函数是否必须使用@Autowired注释?

否。

Spring 4.3之后如果您的类只有一个构造函数,那么就不需要放置@Autowired

在春季4.3之前

package com.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DatabaseAccountService implements AccountService {

    private final RiskAssessor riskAssessor;

    @Autowired
    public DatabaseAccountService(RiskAssessor riskAssessor) {
        this.riskAssessor = riskAssessor;
    }

    // ...

}

<强>后:

@Service
public class DatabaseAccountService implements AccountService {

    private final RiskAssessor riskAssessor;

    public DatabaseAccountService(RiskAssessor riskAssessor) {
        this.riskAssessor = riskAssessor;
    }

    // ...

}