Spring Bean 和依赖注入

您可以自由使用任何标准的 Spring Framework 技术来定义您的 Bean 及其注入的依赖项。我们通常建议使用构造器注入来连接依赖项,并使用 `@ComponentScan` 来查找 Bean。

如果您按照上述建议构建代码(将应用程序类放在顶级包中),则可以添加@ComponentScan(无需任何参数)或使用隐式包含它的@SpringBootApplication注解。所有应用程序组件(@Component@Service@Repository@Controller等)都会自动注册为 Spring Bean。

以下示例显示了一个@Service Bean,它使用构造器注入来获取所需的RiskAssessor bean

  • 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 有多个构造函数,您需要使用@Autowired标记 Spring 要使用的构造函数。

  • 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,表示它不能被后续修改。