Spring Bean 和依赖注入
您可以自由使用任何标准的 Spring Framework 技术来定义 bean 及其注入的依赖项。
我们通常建议使用构造函数注入来连接依赖项,并通过@ComponentScan
查找 bean。
如果按照上述建议构建代码(将应用程序类放在 top 包中),则可以添加不带任何参数的 @ComponentScan
或使用隐式包含它的 @SpringBootApplication
注释。
您的所有应用程序组件(@Service
、@Repository
、@Controller
等)都将自动注册为 Spring Bean。@Component
以下示例显示了一个 @Service
Bean,它使用构造函数注入来获取所需的 Bean:RiskAssessor
-
Java
-
Kotlin
import org.springframework.stereotype.Service;
@Service
public class MyAccountService implements AccountService {
private final RiskAssessor riskAssessor;
public MyAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}
// ...
}
import org.springframework.stereotype.Service
@Service
class MyAccountService(private val riskAssessor: RiskAssessor) : AccountService
如果一个 bean 有多个构造函数,则需要标记你希望 Spring 与 @Autowired
一起使用的构造函数:
-
Java
-
Kotlin
import java.io.PrintStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MyAccountService implements AccountService {
private final RiskAssessor riskAssessor;
private final PrintStream out;
@Autowired
public MyAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
this.out = System.out;
}
public MyAccountService(RiskAssessor riskAssessor, PrintStream out) {
this.riskAssessor = riskAssessor;
this.out = out;
}
// ...
}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.io.PrintStream
@Service
class MyAccountService : AccountService {
private val riskAssessor: RiskAssessor
private val out: PrintStream
@Autowired
constructor(riskAssessor: RiskAssessor) {
this.riskAssessor = riskAssessor
out = System.out
}
constructor(riskAssessor: RiskAssessor, out: PrintStream) {
this.riskAssessor = riskAssessor
this.out = out
}
// ...
}
请注意,使用构造函数注入如何让字段被标记为 ,这表示它随后无法更改。riskAssessor final |