spring核心技术之九:SpEL在Bean中使用

思考:SpEL在Bean中如何使用?

答:SpEL支持在Bean定义时注入,默认使用“#{SpEL表达式}”表示,可以通过XML配置或者注解两种方式实现,注意:此处不允许嵌套,如“#{'Hello'#{world}}”错误,如“#{'Hello' + world}”中“world”默认解析为Bean。

spring核心技术之九:SpEL在Bean中使用

  • 1、XML配置

ApplicationContext实现默认支持SpEL,获取根对象属性其实是获取容器中的Bean。

用SpEL表达式设置属性或者构造函数参数值,如下:





SpEl表达式也可以引入其他bean的属性值,shapeGuess属性值用#{ numberGuess.randomNumber } ,而numberGuess是提前定义好的bean,如下:









其中 systemProperties变量是提前定义好的。

  • 2、注解配置

使用@Value注解来指定SpEL表达式,可以注解在属性、方法和构造函数上,如下:

 public class SimpleMovieLister {

private MovieFinder movieFinder;
//SpEL在属性
@Value("#{ systemProperties['user.region'] }")
private String defaultLocale;
//SpEL在某方法的参数上
@Autowired
public void configure(MovieFinder movieFinder,
@Value("#{ systemProperties['user.Finder'] }") String defaultLocale) {
this.movieFinder = movieFinder;
this.defaultLocale = defaultLocale;
}
}


分享到:


相關文章: