官方文档地址:
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-annotation-config
注解:提供大量的上下文声明, 配置更简短。
XML:擅长连接组件不触碰自己的源代码或重新编译它们。
@Required
注解适用于 bean 属性的 setter 方法,并且它指示受影响的 bean 属性必须在XML配置文件中配置时被填充,否则容器将抛出 BeanInitializationException 异常。
例如:
创建实体类:RequiredDome ,添加 id、name两个属性并添加 @Required 注解。
package com.fengzhi.spring;
import org.springframework.beans.factory.annotation.Required;
public class RequiredDome {
private int id;
private String name;
public int getId() {
return id;
}
@Required
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
@Required
public void setName(String name) {
this.name = name;
}
}
创建 requireDome.xml,添加 requiredDome 并在使用时设置id的值。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd ">
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />
<bean id="requireDome" class="com.fengzhi.spring.RequiredDome">
<property name="id" value="1" />
<!-- <property name="name" value="test" /> -->
</bean>
</beans>
创建测试类 TestRequire :
package com.fengzhi.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.fengzhi.spring.RequiredDome;
public class TestRequire {
@Test
public void testRequire() {
ApplicationContext context = new ClassPathXmlApplicationContext("requireDome.xml");
RequiredDome rd = (RequiredDome) context.getBean("requireDome");
System.out.println("Id: " + rd.getId());
System.out.println("Name : " + rd.getName());
}
}
创建完成后,执行测试类。程序将抛出异常:BeanInitializationException
Initialization of bean failed;
nested exception is org.springframework.beans.factory.BeanInitializationException:
Property 'name' is required for bean 'requireDome'
修改 requireDome .xml :
<?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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd ">
<context:annotation-config />
<bean id="requireDome" class="com.fengzhi.spring.RequiredDome">
<property name="id" value="1" />
<property name="name" value="test" />
</bean>
</beans>
程序即可正常运行。
配置文件中两种不同的配置:
- RequiredAnnotationBeanPostProcessor 是 @Required 注解的处理器,即 bean 后置处理器,检查所有带@Required 的 bean 属性是否设置值,如果未设置值则抛出异常。
- 在spring配置文件中可以通过 <context:annotation-config /> 自动注册RequiredAnnotationBeanPostProcessor 处理器。