Spring 3.0 Required注解检查

Spring 配置文件中 dependency-check 依赖检查的灵活性不够,并不能满足我们所有的需求


Spring还提供一种更加灵活的检查方式 

@Required注解检查 但他只检查属性是否已经设置而不会测试属性是否非空


下面我们看一下如何使用Spring提供的此机制

首先我们需要在程序里面加上注解

[java]  view plain copy
  1. @Required  
  2.     public void setProduct(Product product) {  
  3.         this.product = product;  
  4.     }  

注意@ Required只能设置在setter方法上

接着我们需要在 配置文件中加上这样一句话

[html]  view plain copy
  1. <bean class="org.springframework.beans.factory.annotation.    
  2.     RequiredAnnotationBeanPostProcessor"/>   

这是Spring的一个处理器用于检查

如果Spring的版本是2.5或以上,我们可以直接用下列方式来配置


[html]  view plain copy
  1. <beans  
  2.     xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:p="http://www.springframework.org/schema/p"  
  5.     <span style="color:#ff0000;">xmlns:context="http://www.springframework.org/schema/context"</span>  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  7.     <span style="color:#ff0000;">http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd</span>">  
  8. <span style="color:#ff0000;"><context:annotation-config/></span>  
这是简写形式


这样就配置完成了,这样如果任何带有@Required的属性未设置的话 将会抛出BeanInitializationException异常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值