4.2bean定义中的表达式

可以将SPEL表达式与基于XML或基于注解的配置元数据一起用于定义BeanDefinition实例。在这两种情况下,定义表达式的语法形式都是 #{ <expression string> }。

4.2.1 XML配置

可以使用表达式设置属性或构造函数参数值,如下示例所示:

<bean id="numberGuess" class="org.spring.samples.NumberGuess">
    <property name="randomNumber" value="#{ T(java.lang.Math).random() * 100.0 }"/>

    <!-- other properties -->
</bean>

SystemProperties变量是预定义的,因此可以在表达式中使用它,如下示例所示:

<bean id="taxCalculator" class="org.spring.samples.TaxCalculator">
    <property name="defaultLocale" value="#{ systemProperties['user.region'] }"/>

    <!-- other properties -->
</bean>

注意,在此上下文中,你不必在预定义变量前面加上#符号。

你还可以按名称引用其他bean属性,如下示例所示:

<bean id="numberGuess" class="org.spring.samples.NumberGuess">
    <property name="randomNumber" value="#{ T(java.lang.Math).random() * 100.0 }"/>

    <!-- other properties -->
</bean>

<bean id="shapeGuess" class="org.spring.samples.ShapeGuess">
    <property name="initialShapeSeed" value="#{ numberGuess.randomNumber }"/>

    <!-- other properties -->
</bean>

4.2.2 注解配置

要指定默认值,可以将@value注解放在字段、方法、方法或构造函数参数上。

以下示例设置字段变量的默认值:

下面的示例显示了等效的但在属性设置器方法上的示例:

autowired方法和构造函数也可以使用@value注解,如下示例所示:

最后更新于

这有帮助吗?