Spring的@Required注解

@Required 注释应用于 bean 属性的 setter 方法,是用于检查一个Bean的属性在配置期间是否被赋值。

也就是用确保属性值是否已经设置,检查配置在XML中的Bean的相关属性,是否被注入依赖值。

如果没有注入相关值,那么就会抛出一个BeanInitializationException 异常。

Student.java文件内容如下:

public classStudent{

  private Integer age;

  private String name;

  @Required 

public void setAge(Integer age){//在Set方法上添加注解

      this.age = age;

  }

  publicIntegergetAge(){

      return age;

  }

  @Required 

public void setName(String name){

      this.name = name;

  }

  publicStringgetName(){

      return name;

  }

}

配置文件 ApplicationContext.xml 文件内容:

<?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"    xsi:schemaLocation="http://www.springframework.org/schema/beans

    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

    http://www.springframework.org/schema/context

    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

  <context:annotation-config/>

  <bean id="student" class="com.tutorialspoint.Student">

      <property name="name"  value="Zara" />

      <!-- 将age属性注释 -->

      <!-- property name="age"  value="11"-->

  </bean>

</beans>

这时候运行程序,就会抛出 BeanInitializationException 异常。

org.springframework.beans.factory.BeanInitializationException:Property 'age' is required for bean 'student'

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容