前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java注解研究之@Required

Java注解研究之@Required

作者头像
Jerry Wang
发布2021-02-20 14:43:51
5000
发布2021-02-20 14:43:51
举报

Created by Wang, Jerry on Jul 27, 2016

代码语言:javascript
复制
@Required
 public void setChineseAddressService(final AddressService chineseAddressService)
 {
  this.chineseAddressService = chineseAddressService;
 }

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

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

代码语言:javascript
复制
@Required  
public void setProduct(Product product) {  
    this.product = product;  
 }  

注意@Required只能设置在setter方法上
接着我们需要在 配置文件中加上这样一句话

```xml
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>   

这是Spring的一个处理器用于检查 如果Spring的版本是2.5或以上,我们可以直接用下列方式来配置

代码语言:javascript
复制
<beans   xmlns="http://www.springframework.org/schema/beans"  
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
             xmlns:p="http://www.springframework.org/schema/p"  
   <span style="color:#ff0000;">xmlns:context="http://www.springframework.org/schema/context"</span>  
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  <span style="color:#ff0000;">http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd</span>">  
<span style="color:#ff0000;"><context:annotation-config/></span>  
clipboard1
clipboard1

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-06-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Created by Wang, Jerry on Jul 27, 2016
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档