Spring 解析属性占位符

在Spring装配中,占位符格式:  ${ ... }  使用它包装的属性名称。

如XML配置bean

<bean  id="sgtPeppers"   class  = "com.BalnkDisc"  c:_title="${disc.title}"  c:_artist="${disc.artist}" />

可以看到,title的值是从名称为 disc.title的属性中解析得到的。

如果依赖组件扫描和自动装配来初始化应用组件的话,则可以使用@Value注解

public   BlankDisc(

       @Value("${disc.title}")  String  title,

       @Value("${disc.artist}")  String artist){

this.title=tile;

this.artist= artist;       

}

为了使用占位符,我们必须配置一个PropertyPlaceholderConfigurer或者PropertySourcesPlaceholderConfigurer 的bean,Spring3.1以后,推荐使用后者PropertySourcesPlaceholderConfigurer,因为它能够基于Spring Environment及其属性源来解析占位符。如下:

@Bean

public static   PropertySourcesPlaceholderConfigurer   placeholderConfigurer(){

     return new  PropertySourcesPlaceholderConfigurer();

}

如果你想使用XML配置的话,Spring context命名空间中的<context:property-placeholder >元素将会为你生成 PropertySourcesPlaceholderConfigurer  bean。

在xml中增加如下配置

<context:property-placeholder  />

猜你喜欢

转载自blog.csdn.net/m0_37668842/article/details/82760564
今日推荐