@Required注解适用于bean属性的setter方法,使用@Required的方法必须在xml中填充,负责报错
例如下面的例子中,student中的setAge和setName有@Required注解
如果xml中没有使用<property name="age" value="11">就会报错,
package com.crm; 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; } }
package com.crm; 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() ); } }
<?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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config/> <!-- Definition for student bean --> <bean id="student" class="com.crm.Student"> <property name="name" value="Zara" /> <!-- try without passing age and check the result --> <!-- property name="age" value="11"--> </bean> </beans>