如果我使用构造函数DI,是否必须放置@Autowired
答案 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;
}
// ...
}