Spring 3 では、Bean 定義で使用できる新しい式言語 (SpEL)が導入されました。構文自体はかなり適切に指定されています。
明確ではないのは、SpEL が、以前のバージョンに既に存在していたプロパティ プレースホルダー構文と相互作用する場合、それがどのように相互作用するかです。SpEL はプロパティ プレースホルダーをサポートしていますか? それとも、両方のメカニズムの構文を結合する必要がありますか?
具体例を挙げましょう。プロパティ構文を使用したいのですが、が未定義の場合を処理するためにエルビス演算子${x.y.z}
によって提供される「デフォルト値」構文が追加されています。${x.y.z}
次の構文を試しましたが成功しませんでした:
#{x.y.z?:'defaultValue'}
#{${x.y.z}?:'defaultValue'}
最初のものは私に与えます
タイプ「org.springframework.beans.factory.config.BeanExpressionContext」のオブジェクトにフィールドまたはプロパティ「x」が見つかりません
これは、SpEL がこれをプロパティ プレースホルダーとして認識していないことを示唆しています。
2 番目の構文は、プレースホルダーが認識されないことを示す例外をスローするため、プレースホルダー リゾルバーが呼び出されますが、プロパティが定義されていないため、期待どおりに失敗します。
ドキュメントはこの相互作用について言及していないため、そのようなことは不可能であるか、文書化されていません。
誰でもこれを行うことができましたか?
わかりました、私はこのための小さな自己完結型のテスト ケースを考え出しました。これはすべてそのまま機能します。
まず、Bean の定義:
<?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"
xmlns:util="http://www.springframework.org/schema/util"
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.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
">
<context:property-placeholder properties-ref="myProps"/>
<util:properties id="myProps">
<prop key="x.y.z">Value A</prop>
</util:properties>
<bean id="testBean" class="test.Bean">
<!-- here is where the magic is required -->
<property name="value" value="${x.y.z}"/>
<!-- I want something like this
<property name="value" value="${a.b.c}?:'Value B'"/>
-->
</bean>
</beans>
次に、自明な Bean クラス:
パッケージテスト;
public class Bean {
String value;
public void setValue(String value) {
this.value = value;
}
}
最後に、テスト ケース:
package test;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class PlaceholderTest {
private @Resource Bean testBean;
@Test
public void valueCheck() {
assertThat(testBean.value, is("Value A"));
}
}
${x.y.z}
課題 -解決できない場合にデフォルト値を指定できるようにする、Beans ファイル内の SpEL 式を考え出すこと。このデフォルト値は、別のプロパティ セットで外部化するのではなく、式の一部として指定する必要があります。