Spring基于注解配置(三)
Spring基于注解配置-自动装配
spring利用依赖注入(DI),完成对IOC容器中各个组件的依赖关系赋值
1.@Autowired:自动注入
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Autowired { /** * Declares whether the annotated dependency is required. * <p>Defaults to {@code true}. */ boolean required() default true; }
通过阅读源码发现,@Autowired可以把标识加在构造器上,方法上,参数上,属性上;都是从容器中获取参数组件的值
@Autowired默认在IOC容器中按照类型去找对应的bean实例,如果找到多个相同类型的组件,将属性的名称作为id去容器中寻找
可以使用@Qualifier指定指定装配的组件id,而不是属性名;@Primary可以让spring自动装配的时候使用首选的bean
2.Spring还支持@Resource(JSR250)和@InJect(JSR330)[java规范的注解]
@Resource:
可以和@Autowired一样实现自动装配功能,默认是按照组件名称进行装配的
没有支持@Primary功能没有支持@Autowired(reqiured=false);
@Inject:
需要导入javax.inject的maven包和Autowired一样;没有支持@Autowired(reqiured=false);
4.自定义组件想要使用Spring容器底层的一些组件(ApplicationContext,BeanFactory,xxxx)
@Component public class Red implements ApplicationContextAware,BeanNameAware,EmbeddedValueResolverAware { @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { System.out.println("创建的ioc容器:"+applicationContext); } @Override public void setBeanName(String name) { System.out.println("当前bean的名字:"+name); } @Override public void setEmbeddedValueResolver(StringValueResolver resolver) { String resolveStringValue = resolver.resolveStringValue("你好${os.name},我是#{20*18}"); System.out.println("解析的字符串:"+resolveStringValue); } }
自定义实现xxxAware接口;在创建对象的时候,会调用规定的方法注入相关组件

浙公网安备 33010602011771号