Spring使用@Required註解依賴檢查

Spring依賴檢查 bean 配置文件用於確定的特定類型(基本,集合或對象)的所有屬性被設置。在大多數情況下,你只需要確保特定屬性已經設置但不是所有屬性..

對於這種情況,你需要 @Required 註解,請參見下面的例子:

@Required示例

Customer對象,適用@Required在 setPerson()方法,以確保 person 屬性已設置。

package com.yiibai.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 />
...

完整的實例,

<context:annotation-config />

<bean id="CustomerBean" class="com.yiibai.common.Customer">
    <property name="action" value="buy" />
    <property name="type" value="1" />
</bean>

<bean id="PersonBean" class="com.yiibai.common.Person">
    <property name="name" value="yiibai" />
    <property name="address" value="address ABC" />
    <property name="age" value="29" />
</bean>

2. 包函 RequiredAnnotationBeanPostProcessor

直接在 bean 配置文件包函「RequiredAnnotationBeanPostProcessor」。


<bean id="CustomerBean" class="com.yiibai.common.Customer">
    <property name="action" value="buy" />
    <property name="type" value="1" />
</bean>

<bean id="PersonBean" class="com.yiibai.common.Person">
    <property name="name" value="yiibai" />
    <property name="address" value="address ABC" />
    <property name="age" value="29" />
</bean>    

如果你運行它,下面的錯誤信息會丟的,因爲 person 的屬性未設置。

org.springframework.beans.factory.BeanInitializationException:
Property 'person' is required for bean 'CustomerBean'

結論


嘗試@Required註解,它比依賴檢查XML文件中更加靈活,因爲它可以適用於只有一個特定屬性。

定義@Required
請閱讀本文有關如何創建新的自定義 @Required-style 註解。