Spring的@Required注释

本文内容纲要: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

本文内容总结:Spring的@Required注释

原文链接:https://www.cnblogs.com/pzjtian/p/15328499.html

以上是 Spring的@Required注释 的全部内容, 来源链接: utcz.com/z/296251.html

回到顶部