快捷搜索:  汽车  科技

springbean常用注解(spring核心技术之九SpEL在Bean中使用)

springbean常用注解(spring核心技术之九SpEL在Bean中使用)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; } } <bean id="number

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

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

springbean常用注解(spring核心技术之九SpEL在Bean中使用)(1)

  • 1、XML配置

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

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

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

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

<bean id="numberGuess" class="org.spring.samples.NumberGuess"> <property name="randomNumber" value="#{ T(java.lang.Math).random() * 100.0 }"/> <!-- other properties --> </bean> <ean id="shapeGuess" class="org.spring.samples.ShapeGuess"> <property name="initialShapeSeed" value="#{ numberGuess.randomNumber }"/> <!-- other properties --> </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; } }

猜您喜欢: