版权声明:本文为 小异常 原创文章,非商用自由转载-保持署名-注明出处,谢谢!
本文网址:https://blog.csdn.net/sun8112133/article/details/104312312
疫情之间重温 Spring,发现一个以前没有接触到的注解 —— @Required,正好来个总结。
@Required 注解主要用在 setter 方法上,它表示该 setter 方法的属性必须要在配置时注入值。否则就会报 BeanInitializationException 异常。本篇博客以一个小例子来讲解 @Required 注解的使用。
1、Student 类
先准备一个实体类,这个实体类很简单,只有两个私有属性和两个属性的 setter 方法,并在 setter 方法上用 @Required 注解标注。
public class Student {
private String name;
private Integer age;
@Required
public void setAge(Integer age) {
this.age = age;
}
@Required
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
2、Spring Bean 配置文件
再准备一个 Spring Bean 的配置文件,将上面的实体类(
Student
)配置到 Spring 容器中。在配置文件中只注入一个
name
属性值。
<?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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<!-- 指定要扫面的包,并激活注解 -->
<context:component-scan base-package="com.demo" />
<!-- 配置 student Bean -->
<bean id="student" class="com.demo.Student">
<property name="name" value="sk"></property>
</bean>
</beans>
3、main() 方法
最后来个
main()
方法,用于执行 Spring 程序。
package com.demo;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) ioc.getBean("student");
System.out.println(student);
}
}
如果不出意外,此时会报 BeanInitializationException 异常,并且会输出一些错误信息和其他日志消息。
4、修改配置文件
这个时候我们将
age
的属性值注入进去,代码如下:
<!-- 配置 student Bean -->
<bean id="student" class="com.demo.Student">
<property name="name" value="sk"></property>
<property name="age" value="12"></property>
</bean>
再次执行
main()
方法,程序就会正常执行了,会产生下列结果: