Expressions in Bean Definitions
你可以使用 SpEL 表达式与基于 XML 或基于注解的配置元数据来定义 BeanDefinition 实例。在这两种情况下,定义表达式的语法都是 #{ <表达式字符串> }的形式。
XML 配置
一个属性或构造函数参数值可以通过使用表达式来设置,如下例所示:
<bean id="numberGuess" class="org.spring.samples.NumberGuess"><property name="randomNumber" value="#{ T(java.lang.Math).random() * 100.0 }"/><!-- other properties --></bean>
应用程序上下文中的所有 Bean 都可以作为预定义的变量,以其共同的 Bean 名称来使用。这包括标准的上下文 Bean,如 environment(类型为 org.springframework.core.env.Environment),以及用于访问运行时环境的 systemProperties和 systemEnvironment(类型为 Map<String, Object>)。
下面的例子显示了对作为 SpEL 变量的 systemProperties bean 的访问:
<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>
注解配置
为了指定一个默认值,你可以在字段、方法和方法或构造函数参数上放置 @Value注解。
下面的例子设置了一个字段的默认值:
package cn.mrcode.study.springdocsread.web;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;/*** @author mrcode*/@Componentpublic class DemoService {// user.region 这个 key 有可能是空的,所以在测试的时候换另外一个 容易看出来效果// @Value("#{ systemProperties['user.region'] }")@Value("#{ systemProperties['user.country'] }")private String defaultLocale;}
下面的例子是等价的,但在一个属性设置方法上:
public class PropertyValueTestBean {private String defaultLocale;@Value("#{ systemProperties['user.region'] }")public void setDefaultLocale(String defaultLocale) {this.defaultLocale = defaultLocale;}public String getDefaultLocale() {return this.defaultLocale;}}
自动装配的方法和构造函数也可以使用 @Value注解,正如下面的例子所示:
public class SimpleMovieLister {private MovieFinder movieFinder;private String defaultLocale;@Autowiredpublic void configure(MovieFinder movieFinder,@Value("#{ systemProperties['user.region'] }") String defaultLocale) {this.movieFinder = movieFinder;this.defaultLocale = defaultLocale;}// ...}
public class MovieRecommender {private String defaultLocale;private CustomerPreferenceDao customerPreferenceDao;public MovieRecommender(CustomerPreferenceDao customerPreferenceDao,@Value("#{systemProperties['user.country']}") String defaultLocale) {this.customerPreferenceDao = customerPreferenceDao;this.defaultLocale = defaultLocale;}// ...}
