@Required注解适用于bean属性的setter方法并且它指示,受影响的bean属性必须在配置时被填充在XML配置文件中,否则容器将抛出BeanInitializationException例外。下面是一个例子,说明使用@ Required注解。
例子:
我们使用Eclipse IDE,然后按照下面的步骤来创建一个Spring应用程序:
步骤
描述
1
Create a project with a name SpringExample and create a package com.yiibai under the src folder in the created project.
2
Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3
Create Java classes Student and MainApp under the com.yiibai package.
4
Create Beans configuration file Beans.xml under the src folder.
5
The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.
这里是Student.java文件的内容:
packagecom.yiibai;importorg.springframework.beans.factory.annotation.Required;publicclassStudent{privateIntegerage;privateStringname;@RequiredpublicvoidsetAge(Integerage){this.age=age;}publicIntegergetAge(){returnage;}@RequiredpublicvoidsetName(Stringname){this.name=name;}publicStringgetName(){returnname;}}
以下是MainApp.java文件的内容:
packagecom.yiibai;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;publicclassMainApp{publicstaticvoidmain(String[]args){ApplicationContextcontext=newClassPathXmlApplicationContext("Beans.xml");Studentstudent=(Student)context.getBean("student");System.out.println("Name : "+student.getName());System.out.println("Age : "+student.getAge());}}
以下是配置文件beans.xml中的内容:
<?xml version="1.0"encoding="UTF-8"?>
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">
一旦创建源代码和bean配置文件完成后,让我们运行应用程序。如果一切顺利,这将抛出BeanInitializationException异常,并与其他日志信息打印以下错误:
Property 'age' is required for bean 'student'
接下来,可以从“age”属性中删除注释如下尝试后,上面的例子:
<?xml version="1.0"encoding="UTF-8"?>
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">
现在,上面的例子会产生以下结果:
Name : Zara
Age : 11
¥ 我要打赏
纠错/补充
收藏
加QQ群啦,易百教程官方技术学习群
注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。