@Autowired如果我使用构造函数DI,是否必须填写?
@Autowired
@Autowired注释对于构造函数是必需的吗?
没有。
在Spring 4.3之后,如果您的类只有单个构造函数,则无需放置@Autowired。
在Spring 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; } // ... }