ITPub博客

首页 > IT职业 > IT生活 > Spring @Required 注释

Spring @Required 注释

IT生活 作者:greatleaf 时间:2021-09-09 08:54:14 0 删除 编辑

Spring @Required 注释

@Required 注释应用于 bean 属性的 setter 方法,它表明受影响的 bean 属性在配置时必须放在 XML 配置文件中,否则容器就会抛出一个 BeanInitializationException 异常。下面显示的是一个使用 @Required 注释的示例。

示例:

让我们使 Eclipse IDE 处于工作状态,请按照下列步骤创建一个 Spring 应用程序:

步骤 描述
1 创建一个名为 SpringExample 的项目,并且在所创建项目的 src 文件夹下创建一个名为 com.tutorialspoint 的包。
2 使用 Add External JARs 选项添加所需的 Spring 库文件,就如在 Spring Hello World Example 章节中解释的那样。
3 在 com.tutorialspoint 包下创建 Java 类 Student 和 MainApp。
4 在 src 文件夹下创建 Beans 配置文件 Beans.xml。
5 最后一步是创建所有 Java 文件和 Bean 配置文件的内容,并且按如下解释的那样运行应用程序。

下面是 Student.java 文件的内容:

package com.tutorialspoint; 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 文件的内容:

package com.tutorialspoint; 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: 文件的内容:

         <!-- Definition for student bean -->                  <!-- try without passing age and check the result -->       <!-- property name="age"  value="11"-->     


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4236/viewspace-2797895/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-12

  • 博文量
    76
  • 访问量
    610