Spring的@Required注释

大多数情况下,我们不必为Bean的所有属性设值,如果确保属性必须要设置,就使用@Required注解,标识在set方法上,检查属性是否设置有值。

/**
 ** @Required注解用来检查age属性是否有设置值
 */
public class Student {

  private String name;
  private int age;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  @Required
  public void setAge(int age) {
    this.age = age;
  }
}

仅仅只是使用@Required注解并不能起到依赖检查的效果,还需要注册一个RequiredAnnotationBeanPostProcessor,两种方式:

1.直接将RequiredAnnotationBeanPostProcessor注册成Bean

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

2.引入context:annotation-config配置,该配置包括AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor

<?xml version="1.0" encoding="UTF-8"?>
<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"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

 <context:annotation-config />

 <bean id="Student" class="org.source.demo.Student">
  <property name="name" value="jack" />
 </bean>

</beans>

如果你的Student Bean中没有设置age属性的值,运行就会出错

Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanInitializationException: Property 'age' is required for bean 'Student'
自定义Required注释

如果你的项目中有自己的Required注释,Spring允许你自定义自己的注解,并可以注册到Spring中,相当于@Required

1.自定义注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyRequired {

}

2.注解应用到属性

public class Student {

  private String name;
  private int age;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  @MyRequired
  public void setAge(int age) {
    this.age = age;
  }
}

3.将注解注册到RequiredAnnotationBeanPostProcessor

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor">
   <property name="requiredAnnotationType" value="org.source.demo.MyRequired" />
 </bean>

这样就完成了自定义注解@MyRequired,相当于@Required

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值