目录
8.@PostConstruct and @PreDestory
基于注解的容器配置
5.使用泛型作为自动装配修饰语
@Autowired
private Store<String> s1; // <String> qualifier, injects the stringStore bean
@Autowired
private Store<Integer> s2; // <Integer> qualifier, injects the integerStore bean
note:Store是泛型接口,使用不同类型实现的bean进行注入。
ps:除了使用@Qualifier注解,泛型的类型也可以用于确认注入的依赖bean。
6.CustomAutowireConfigure
<bean id="customAutowireConfigurer"
class="org.springframework.beans.factory.annotation.CustomAutowireConfigurer">
<property name="customQualifierTypes">
<set>
<value>example.CustomQualifier</value>
</set>
</property>
</bean>
ps:CustomAutowireConfigure是一个BeanFactoryPostProcessor的实现,用于注册自制的修饰符注解类型,即使这些注解类型没有使用@Qualifier进行注解。
AutowireCandidateResolver决定自动装配候选的依据:
- 每一个bean定义的autowire-candidate值
- 任何<beans/>元素上可能的default-autowire-candidates模式
- @Qualifier注解以及注册在CustomAutowireConfigurer上的自定义注解
7.@Resource
public class Example {
private Foo foo;
@Resource(name="foo")
public void setFoo(Foo foo) {
this.foo = foo;
}
}
note:将名为foo的bean通过Example的setter方法注入。
ps:如果没有显式为@Resource注解指定值,那么注入时使用的默认bean名称为域名或属性名。
ps:不使用显示名称的@Resource与@Autowire类似,即查找使用基本类型匹配而不是特定名称bean,以及解析well-known可解析依赖:BeanFactory、ApplicationContext、ResourceLoader、ApplicationEventPublisher、MessageSource。
public class Example {
@Resource
private Foo foo;
@Resource
private ApplicationContext context;
}
note:foo域首先查找名为foo的域,然后退步查找类型匹配Foo的bean。
note:context被可解析依赖类型ApplicationContext注入。
由注解提供的名称,通过被CommonAnnotationBeanPostProcessor意识到的ApplicationContext被解析为一个bean名称。
如果显式配置了Spring的SimpleJndiBeanFactory,那么名称便可以被解析。
不过,推荐依赖默认行为与简单使用JNDI查找能力去保持间接水平。
8.@PostConstruct and @PreDestory
public class Example {
@PostConstruct
public void actionA() {
}
@PreDestroy
public void actionB() {
}
}
note:actionA()设置为initialization 回掉方法。
note:actionB()设置为destruction回调方法。