spring_reference/III. Using Spring Boot/17. Spring Beans and depend...

28 lines
1.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

### 17. Spring Beans和依赖注入
你可以自由地使用任何标准的Spring框架技术去定义beans和它们注入的依赖。简单起见我们经常使用`@ComponentScan`注解搜索beans并结合`@Autowired`构造器注入。
如果使用上面建议的结构组织代码(将应用类放到根包下),你可以添加`@ComponentScan`注解而不需要任何参数。你的所有应用程序组件(`@Component`, `@Service`, `@Repository`, `@Controller`将被自动注册为Spring Beans。
下面是一个`@Service` Bean的示例它使用构建器注入获取一个需要的`RiskAssessor` bean。
```java
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;
}
// ...
}
```
**注**:注意如何使用构建器注入来允许`riskAssessor`字段被标记为`final`,这意味着`riskAssessor`后续是不能改变的。