java required注解_Spring @Required 注释

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

下面显示的是一个使用 @Required 注释的示例。

新建一个Spring项目

创建 Java 类 Student 和 MainApp

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

package hello;

import org.springframework.beans.factory.annotation.Required;

public class Student {

private int age;

String name;

@Required

public void setAge(int age){

this.age = age;

}

public int getAge(){

return age;

}

@Required

public void setName(String name){

this.name = name;

}

public String getName(){

return name;

}

}

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

package hello;

//import org.springframework.context.support.AbstractApplicationContext;

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: 文件的内容:

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">

运行结果如下:

name: fanqie

age: 20

总结:

1、要在使用@Required 注释的java文件中引入:

import org.springframework.beans.factory.annotation.Required;

2、配置文件Beans.xml的前面要如下书写,否则会出错:

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">

3、 bean 属性的 setter 方法在配置时必须放在 XML 配置文件中,否则会出错

@Required

public void setAge(Integer age) {

this.age = age;

}

@Required

public void setName(String name) {

this.name = name;

}

如上面有两个setter方法,则age和nama属性都必须放在XML配置文件中。

每天学习一点点,每天进步一点点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值