Spring依賴檢查 bean 配置檔用於確定的特定類型(基本,集合或對象)的所有屬性被設置。在大多數情況下,你只需要確保特定屬性已經設置但不是所有屬性..
對於這種情況,你需要 @Required 注解,請參見下麵的例子:
@Required示例
Customer對象,適用@Required在 setPerson()方法,以確保 person 屬性已設置。
package com.xuhuhu.common; import org.springframework.beans.factory.annotation.Required; public class Customer { private Person person; private int type; private String action; public Person getPerson() { return person; } @Required public void setPerson(Person person) { this.person = person; } }
簡單地套用@Required注解不會強制執行該屬性的檢查,還需要註冊一個RequiredAnnotationBeanPostProcessor以瞭解在bean配置檔@Required注解。
RequiredAnnotationBeanPostProcessor可以用兩種方式來啟用。
1. 包函 <context:annotation-config />
添加 Spring 上下文和 <context:annotation-config />在bean配置檔。
<beans ... xmlns:context="http://www.springframework.org/schema/context" ... http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> ... <context:annotation-config /> ... </beans>
完整的實例,
<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-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:annotation-config /> <bean id="CustomerBean" class="com.xuhuhu.common.Customer"> <property name="action" value="buy" /> <property name="type" value="1" /> </bean> <bean id="PersonBean" class="com.xuhuhu.common.Person"> <property name="name" value="zaixian" /> <property name="address" value="address ABC" /> <property name="age" value="29" /> </bean> </beans>
2. 包函 RequiredAnnotationBeanPostProcessor
直接在 bean 配置檔包函“RequiredAnnotationBeanPostProcessor”。
<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-2.5.xsd"> <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/> <bean id="CustomerBean" class="com.xuhuhu.common.Customer"> <property name="action" value="buy" /> <property name="type" value="1" /> </bean> <bean id="PersonBean" class="com.xuhuhu.common.Person"> <property name="name" value="zaixian" /> <property name="address" value="address ABC" /> <property name="age" value="29" /> </bean> </beans>
如果你運行它,下麵的錯誤資訊會丟的,因為 person 的屬性未設置。
org.springframework.beans.factory.BeanInitializationException: Property 'person' is required for bean 'CustomerBean'
結論
嘗試@Required注解,它比依賴檢查XML檔中更加靈活,因為它可以適用於只有一個特定屬性。
定義@Required
請閱讀本文有關如何創建新的自定義 @Required-style 注解。
請閱讀本文有關如何創建新的自定義 @Required-style 注解。
上一篇:
Spring依賴檢查
下一篇:
Spring自定義@Required-style注解