扫码一下
查看教程更方便
@Required 注释适用于 bean 属性设置器方法,它表明受影响的 bean 属性必须在配置时填充到 XML 配置文件中。 否则,容器会抛出 BeanInitializationException 异常。 下面是一个例子来展示@Required 注解的使用。
在 com.jiyik 包下创建 Java 类 Student 和 MainApp。
这是 Student.java 文件的内容
Student.java
package com.jiyik; import org.springframework.beans.factory.annotation.Required; public class Student { private Integer age; private String name; @Required public void setAge(Integer age) { this.age = age; } public Integer getAge() { return age; } @Required public void setName(String name) { this.name = name; } public String getName() { return name; } }
以下是 MainApp.java 文件的内容
MainApp.java
package com.jiyik; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); Student student = (Student) context.getBean("student"); System.out.println("Name : " + student.getName() ); System.out.println("Age : " + student.getAge() ); } }
以下是配置文件Beans.xml的内容
Beans.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/> <!-- Definition for student bean --> <bean id = "student" class = "com.jiyik.Student"> <property name = "name" value = "Zara" /> <!-- try without passing age and check the result --> <!-- property name = "age" value = "11"--> </bean> </beans>
完成源代码和 bean 配置文件后,让我们运行应用程序。 如果应用程序一切正常,它将引发 BeanInitializationException 异常并打印以下错误以及其他日志消息
Property 'age' is required for bean 'student'
接下来,可以在从 'age' 属性中删除评论后尝试上面的示例,如下所示
<?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/>
<!-- Definition for student bean -->
<bean id = "student" class = "com.jiyik.Student">
<property name = "name" value = "Zara" />
<property name = "age" value = "11"/>
</bean>
</beans>
打印结果如下所示
Name : Zara
Age : 11