Spring Beans and Dependency Injection
你可以使用任何标准 Spring Framework 技术来定义 Bean 及其注入的依赖项。我们通常建议使用构造函数注入来连接依赖项,并使用 `@ComponentScan`查找 Bean。
You are free to use any of the standard Spring Framework techniques to define your beans and their injected dependencies.
We generally recommend using constructor injection to wire up dependencies and @ComponentScan
to find beans.
如果你将代码按上述建议进行构建(将应用程序类置于顶级包中),则可以添加 @ComponentScan
,而无需任何参数,或者使用隐式包含它的 @SpringBootApplication`注释。所有应用程序组件(
@Component`、@Service
、@Repository
、`@Controller`和其他)都会自动注册为 Spring Bean。
If you structure your code as suggested above (locating your application class in a top package), you can add @ComponentScan
without any arguments or use the @SpringBootApplication
annotation which implicitly includes it.
All of your application components (@Component
, @Service
, @Repository
, @Controller
, and others) are automatically registered as Spring Beans.
下面的示例显示了一个 `@Service`Bean,它使用构造函数注入来获取一个必需的 `RiskAssessor`Bean:
The following example shows a @Service
Bean that uses constructor injection to obtain a required RiskAssessor
bean:
如果一个 Bean 有多个构造函数,则需要标记要让 Spring 使用的构造函数,方法是使用 @Autowired
:
If a bean has more than one constructor, you will need to mark the one you want Spring to use with @Autowired
:
请注意,使用构造函数注入如何让 |
Notice how using constructor injection lets the |