spring之通过@Required注解检查属性

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的配置

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值