# 6.5. Spring Bean 和依赖注入

您可以自由地使用任何标准 Spring 框架技术来定义您的 bean 及其注入的依赖项。我们通常建议使用构造函数注入来连接依赖项并通过`@ComponentScan`查找 bean。

如果您按照上面的建议构建代码（将应用程序类定位在顶级包中），则可以在`@ComponentScan`不添加任何参数的情况下添加或使用`@SpringBootApplication`隐式包含`@ComponentScan`注释。您的所有应用程序组件（`@Component`、`@Service`、`@Repository`、`@Controller`和其他）都会自动注册为 Spring Bean。

以下示例显示了使用构造函数注入来获取所需 `@Service`bean 的`RiskAssessor` Bean：

```
@Service
public class MyAccountService implements AccountService {
​
    private final RiskAssessor riskAssessor;
​
    public MyAccountService(RiskAssessor riskAssessor) {
        this.riskAssessor = riskAssessor;
    }
​
    // ...
​
}
```

如果一个 bean 有多个构造函数，您需要通过`@Autowired`标记您希望 Spring 使用的构造函数：

```
@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;
    }
​
    // ...
​
}
```

> 请注意如何使用构造函数注入将`riskAssessor`字段标记为`final`，表示随后无法对其进行更改。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://doc.shiker.tech/spring-boot-can-kao-wen-dang/6.-shi-yong-spring-boot-jin-xing-kai-fa/6.5.-spring-bean-he-yi-lai-zhu-ru.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
