原课程:通过注解注入Bean
注入bean知识点思维导图
Spring 4.x推荐使用基于构造器的方式进行bean注入7.4.1 Dependency Injection
spring为什么推荐使用构造器注入
通过构造器和Set方法注入Bean
注意:通过构造器注入Bean时,如果只有一个构造器,可以不写@Autowired注解,详见17. Spring Beans and Dependency Injection
The following example shows a @Service Bean that uses constructor injection to obtain a required RiskAssessor bean:
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;
}
// ...
}
If a bean has one constructor, you can omit the @Autowired, as shown in the following example:
@Service
public class DatabaseAccountService implements AccountService {
private final RiskAssessor riskAssessor;
public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}
// ...
}
通过属性直接注入Bean
实例化和注入时指定Bean的ID
List/Set注入
直接注入List实例
将多个泛型实例注入到List
Map注入
直接注入Map实例
将多个泛型实例注入到Map
把某个类型的bean组成一个Map或者List注入到另一个bean中,可以使用@Autowired或@Resource实现。
springboot注入@autowire——Map/List