java spring required,Spring @Required注释

@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 个群。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值