Spring Properties使用的几种方式

1.PropertyPlaceholderConfigurer类

org.springframework.beans.factory.config.PropertyPlaceholderConfigurer

  • 使用PropertyPlaceholderConfigurer方式加载的配置键值,可以在xml文件中通过${***}占位符引入,也可以在类(class)中通过@Value("${***}")注解在变量上注入值。


/** 在java类中的使用方式 **/
@Value("${***}")
private String ***;
  • locations参数 支持String[]类型,可以同时传入多个配置文件的地址(支持*通配符填入地址)。

    
        
            classpath:resource1.properties
            classpath:config/resource2.properties
            classpath*:resource3.properties
        
    

2. context:property-placeholder标签

  • 使用方法同PropertyPlaceholderConfigurer类的方式相同,可以在xml文件中通${***}占位符引入,也可以在类(class)中通过@Value("${***}")注解在变量上注入值。
  • 需要在beans配置文件中,声明context纲要属性。

  • 使用context提供的proerty-placeholder标签加载配置文件,在location参数填入需要加载文件的路径,多个文件使用逗号分隔(注意:多个文件都需要填写各自的完整路径)。

  • 如果在beans配置文件中多次定义并加载该标签,则只有最先被加载的标签生效。
  • 如果在该标签的location参数中引入的文件有重复的键值,则靠后(更右侧会更晚加载)的资源文件中的键值,会覆盖靠前的已加载的键值。

3.PropertiesFactoryBean类

org.springframework.beans.factory.config.PropertiesFactoryBean

  • 使用#{BeanID['***']}的方式注入键值,不能使用PropertiesFactoryBean类注入键值的方法(即${***}格式不能注入PropertiesFactoryBean加载的键值)。


    
        
            classpath:resource1.properties
            classpath:config/resource2.properties
            classpath*:resource3.properties
        
    



/** 在java类中的使用方式 **/
@Value("#{proertiesHolder['***']}")
private String ***;

你可能感兴趣的:(Spring Properties使用的几种方式)