| 依赖注入类型 | 配置元数据举例 |
|---|---|
| Setter 方法 | <proeprty name="user" ref="userBean"/> |
| 构造器 | <constructor-arg name="user" ref="userBean" /> |
| 字段 | @Autowired User user; |
| 方法 | @Autowired public void user(User user) { ... } |
| 接口回调 | class MyBean implements BeanFactoryAware { ... } |
参考枚举:org.springframework.beans.factory.annotation.Autowire
| 模式 | 说明 |
|---|---|
| no | 默认值,未激活 Autowiring,需要手动指定依赖注入对象。 |
| byName | 根据被注入属性的名称作为 Bean 名称进行依赖查找,并将对象设置到该属性。 |
| byType | 根据被注入属性的类型作为依赖类型进行查找,并将对象设置到该属性。 |
| constructor | 特殊 byType 类型,用于构造器参数。 |
实现方法
API配置元信息
自动模式
constructor -- 特殊的bytype
| 內建接口 | 说明 |
|---|---|
| BeanFactoryAware | 获取 IoC 容器 - BeanFactory |
| ApplicationContextAware | 获取 Spring 应用上下文 - ApplicationContext 对象 |
| EnvironmentAware | 获取 Environment 对象 |
| ResourceLoaderAware | 获取资源加载器 对象 - ResourceLoader |
| BeanClassLoaderAware | 获取加载当前 Bean Class 的 ClassLoader |
| BeanNameAware | 获取当前 Bean 的名称 |
| MessageSourceAware | 获取 MessageSource 对象,用于 Spring 国际化 |
| ApplicationEventPublisherAware | 获取 ApplicationEventPublishAware 对象,用于 Spring 事件 |
| EmbeddedValueResolverAware | 获取 StringValueResolver 对象,用于占位符处理 |
延迟依赖注入
集合类型
使用API ObjectProvider 延迟注入(推荐)
单一类型
集合类型
使用 API ObjectFactory 延迟注入
使用 API ObjectProvider 延迟注入(推荐)
DefaultListableBeanFactory#resolveDependency@Autowired、@Inject 注入,参考 AutowiredAnnotationBeanPostProcessor
CommonAnnotationBeanPostProcessorAutowiredAnnotationBeanPostProcessor 实现org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor
@Autowired@Value@Inject@PostConstruct@PreDestroy初始化 Bean 时,AutowiredAnnotationBeanPostProcessor 先解析 Bean 中的依赖(@Autowire,@Value),然后 CommonAnnotationBeanPostProcessor 调用初始化方法 @@PostConstruct
将 @Bean 方法设置为 static ,可以让 Bean 提前初始化。
ApplicationContext#getBeanorg.springframework.beans.factory.support.DefaultListableBeanFactory#resolveDependency1、有多少种依赖注入的方式?
2、偏好构造器注入还是setter注入?
3、spring依赖注入的来源有哪些?