spring之通过@Required注解检查属性
----------
Spring的依赖检查特性只能检查某些类型的所有属性。这很不灵活,它不能只针对个别属性时行检查。在大多数情况下,你只想检查个别属性是否已被设置,并不想对特定类型的所有属性都进行检查。
这时,我们可以通过@Required注解进行检查。RequiredAnnotationBeanPostProcessor是Spring的Bean后置处理器,它会检查所有具有@Required注解的属性是否已被设置。Bean后置处理器是一种特殊类型的Spring Bean,它能够在每个Bean实例化后执行一些额外的工作。要激活该Bean后置处理器来进行属性检查,必须在Spring IOC容器里注册它。需要注意的是,该处理器只能检查属性是否已被设置,对属性是否为null无能为力。
示例:
package com.apress.springrecipes.sequence;
import org.springframework.beans.factory.annotation.Required;
public class SequenceGenerator{
private PrefixGenerator prefixGenerator;
private String suffix;
...
@Required
public void setPrefixGenerator(PrefixGenerator prefixGenerator){
this.prefixGenerator = prefixGenerator;
}
@Required
public void setSuffix(String suffix){
this.suffix = suffix;
}
...
}
要让Spring检查实例上的这些属性是否已被设置,则必须在IOC容器里注册一个RequiredAnnotationBeanPostProcessor实例。如果使用的是Bean Factory,则必须通过API注册该Bean后置处理器。但如果使用的是Application Context,那么恭喜,只需要为该后置处理器声明一个实例即可。
<bean class="org.springframework.beans.factory.annotation. RequiredAnnotationBeanPostProcessor"/>
如果正在使用的是Spring2.5,那么更简单,在Bean配置文件里包含<context:annotation-config>元素即可,此时,RequiredAnnotationBeanPostProcessor实例将自动被注册。
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:annotation-config/> ... </beans>
如果任何具有@Required注解的属性未被设置,该Bean后置处理器将抛出BeanInitializationException。
注意:上面的示例中,增加了spring-context的配置。