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;
}
}


分享到:


相關文章: