Spring自动注入
@Autowired 自动注入
1.默认优先使用类型匹配组件
2.如果找到多个 再根据组件名字查找
3.使用@Qualifier("person") 注解明确指定需要装配的组件id
4.默认IOC容器中必须要有组件 可以用@Autowired 注解的属性 @Autowired(required = false) 指定该组件不是必须的
5.@Primary 首选装配bean
6.该注解功能是AutowiredAnnotationBeanPostProcessor 类 支持和实现的
7.该注解可以在构造器、方法、属性、注解、参数上添加
1)标注在方法上 Spring容器创建当前对象 就会调用方法完成赋值 方法的参数是从IOC容器中获取
2)标记在构造器方法上 (只有一个有参构造器可以省略)
3)标记在方法参数上
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
boolean required() default true;
}
Spring还支持使用 @Resource(JSR250)和@InJect(JSR330) java规范的注解
@Resource 默认按照名称进行装配 但 不支持@Primary @Autowired(required = false) 功能
@Inject 需要导入 javax.inject的包 使用与@Autowired 一样 没有@Autowired(required = false) 功能
- 自定义组件想要使用Spring容器底层的一些组件 (ApplicationContext,BeanFactory ,。。。。) 自定义组件可以实现xxxAware 接口
例如
public interface ApplicationContextAware extends Aware {
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}
实现ApplicationContextAware 接口 ioc容器会在对应的后置处理器 ApplicationContextAwareProcessor 类中回调接口中的方法
@Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
AccessControlContext acc = null;
if (System.getSecurityManager() != null &&
(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
acc = this.applicationContext.getBeanFactory().getAccessControlContext();//回调函数
}
if (acc != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
invokeAwareInterfaces(bean);
return null;
}
}, acc);
}
else {
invokeAwareInterfaces(bean);
}
return bean;
}