@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'
网友评论