Spring框架读取property属性文件常用5种方法

 更新时间:2020年09月27日 10:17:45   作者:爱笑的berg  
这篇文章主要介绍了Spring框架读取property属性文件常用5种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

1、方式一:通过spring框架 PropertyPlaceholderConfigurer 工具实现

<bean id="propertyConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="ignoreUnresolvablePlaceholders" value="true"/>
    <property name="locations">
      <value>classpath:conf/jdbc.properties</value>
    </property>
    <property name="fileEncoding">
      <value>UTF-8</value>
    </property>
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
  </bean>
  
  <!-- 数据源配置 -->
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
     destroy-method="close">
    <property name="driverClassName" value="${database.connection.driver}"/>
    <property name="url" value="${database.connection.url}"/>
    <property name="username" value="${database.connection.username}"/>
    <property name="password" value="${database.connection.password}"/>
  </bean>
  <!-- DAL客户端接口实现->
  <bean id="dalClient" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"/>
  </bean>

2、方式二:简化配置

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
  http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
  ">
  <context:property-placeholder location="classpath:conf/jdbc.properties" ignore-unresolvable="true"/>
  <!-- 数据源配置 -->
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
     destroy-method="close">
    <property name="driverClassName" value="${database.connection.driver}"/>
    <property name="url" value="${database.connection.url}"/>
    <property name="username" value="${database.connection.username}"/>
    <property name="password" value="${database.connection.password}"/>
  </bean>
  <!-- DAL客户端接口实现-->
  <bean id="dalClient" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"/>
  </bean>
  <!--备注:如果${} 这种写法无法读取到,或者编译出错,则增加ignore-unresolvable="true"的属性信息,并添加上文的 命名空间信息-->
  
  jdbc.properties文件:
  database.connection.driver=com.mysql.jdbc.Driver
  database.connection.url=jdbc:mysql://*.*.*.*:3306/mysql?characterEncoding=utf-8
  database.connection.username=*
  database.connection.password=*

上述配置理解:

1)ignore-unresolvable属性的示意:

<xsd:documentation><![CDATA[
Specifies if failure to find the property value to replace a key should be ignored.
Default is "false", meaning that this placeholder configurer will raise an exception
if it cannot resolve a key. Set to "true" to allow the configurer to pass on the key
to any others in the context that have not yet visited the key in question.
]]>

翻译后:指定是否应忽略未能找到用于替换键的属性值。默认值为“false”,表示如果它无法解析密钥,此占位符配置程序将引发异常。设置为“true”以允许配置程序传递密钥对于上下文中尚未访问相关密钥的任何其他用户。

2) 为简化 PropertyPlaceholderConfigurer 的使用,Spring提供了<context:property-placeholder location="classpath:jdbc.properties" />元素,启用它后,开发者便不用配置PropertyPlaceholderConfigurer对象了。

PropertyPlaceholderConfigurer内置的功能非常丰富,如果它未找到${xxx}中定义的xxx键,它还会去JVM系统属性(System.getProperty())和环境变量(System.getenv())中寻找。其通过启用systemPropertiesMode和searchSystemEnvironment属性,开发者能够控制这一行为。context:property-placeholder大大的方便了我们数据库的配置。这样就可以为spring配置的bean的属性设置值了。

备注:spring容器中最多只能定义一个 context:property-placeholder,否则会报错:Could not resolve placeholder XXX,但如果想引入多个属性文件怎么办那,可以使用通配符:<context:property-placeholder location="classpath*:conf*.properties"/>

3、方式三:通过对spring PropertyPlaceholderConfigurer bean工厂后置处理器的实现,在java程序中进行属性文件的读取

<bean id="propertyConfigurer" class="com.weblearn.utils.PropertyConfigurer">
    <property name="locations">
      <list>
        <value>classpath:conf/web-sys-relation.properties</value>
        <value>classpath:conf/jdbc.properties</value>
        <value>classpath:conf/main-setting-web.properties</value>
      </list>
    </property>
    <property name="fileEncoding" value="UTF-8"/>
  </bean>
  <!-- DAL客户端接口实现-->
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
     destroy-method="close">
    <property name="driverClassName" value="${database.connection.driver}"/>
    <property name="url" value="${database.connection.url}"/>
    <property name="username" value="${database.connection.username}"/>
    <property name="password" value="${database.connection.password}"/>
  </bean>
  
  <bean id="dalClient" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"/>
  </bean>
public class PropertyConfigurer extends PropertyPlaceholderConfigurer {
    /* 
      PropertyPlaceholderConfigurer 是个bean工厂后置处理器的实现,也就是 BeanFactoryPostProcessor 接口的一个实现。
      在Spring中,使用PropertyPlaceholderConfigurer可以在XML配置文件中加入外部属性文件,当然也可以指定外部文件的编码。PropertyPlaceholderConfigurer可以将上下文
    (配置文 件)中的属性值放在另一个单独的标准java Properties文件中去。在XML文件中用${key}替换指定的properties文件中的值。这样的话,只需要对properties文件进
    行修改,而不用对xml配置文件进行修改。
      引入外部文件后,就可以在xml中用${key}替换指定的properties文件中的值,通常项目中都会将jdbc的配置放在properties文件中。
      在启动容器时,初始化bean时,${key}就会替换成properties文件中的值。
    */

    //存取properties配置文件key-value结果
    private Properties props;

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
        throws BeansException {
      super.processProperties(beanFactoryToProcess, props);
      this.props = props;
    }

    public String getProperty(String key) {
      return this.props.getProperty(key);
    }

    public String getProperty(String key, String defaultValue) {
      return this.props.getProperty(key, defaultValue);
    }

    public Object setProperty(String key, String value) {
      return this.props.setProperty(key, value);
    }

  }

  @Controller
  @RequestMapping("/")
  public class TestController {
    @Autowired
    PropertyConfigurer propertyConfigurer;

    @RequestMapping("/index.do")
    public String getIndex(HttpServletRequest request, HttpServletResponse response, Model model) {
      Map map = new HashMap<String, Object>();
      map.put("orderNo", "111");

      String address1 = propertyConfigurer.getProperty("static.picture.address1");
      String resRoot = propertyConfigurer.getProperty("resRoot");
      String envName = propertyConfigurer.getProperty("database.connection.username");
      String keyzjbceshi = propertyConfigurer.getProperty("keyceshi");


      map.put("address1", address1);
      map.put("resRoot", resRoot);
      map.put("envName", envName);
      map.put("keyzjbceshi", keyzjbceshi);

      model.addAllAttributes(map);
      return "index/index.ftl";
    }
  }

4、方式四:通过ClassPathResource类进行属性文件的读取使用

public class ReadPropertiesUtils1 {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReadPropertiesUtils1.class);

    private static Properties props = new Properties();

    static {
      ClassPathResource cpr = new ClassPathResource("conf/ref-system-relation.properties");// 会重新加载spring框架
      try {
        props.load(cpr.getInputStream());
      } catch (IOException exception) {
        LOGGER.error("ReadPropertiesUtils1 IOException", exception);
      }
    }

    private ReadPropertiesUtils1() {

    }

    public static String getValue(String key) {
      return (String) props.get(key);
    }

    public static void main(String[] args) {
      System.out.println("static.picture.address1>>>"+ ReadPropertiesUtils1.getValue("static.picture.address1"));
      System.out.println("static.picture.address2>>>"+ ReadPropertiesUtils1.getValue("static.picture.address2"));
    }

  }

5、方式五:通过ContextClassLoader进行属性文件的读取使用

public class ReadPropertiesUtils2 {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReadPropertiesUtils2.class);

    public static String getValue(String key) {
      Properties properties = new Properties();
      try {
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("conf/ref-system-relation.properties");
        properties.load(inputStream);
      } catch (FileNotFoundException e) {
        LOGGER.error("conf/web-sys-relation.properties文件没有找到异常", e);
      } catch (IOException e) {
        LOGGER.error("IOException", e);
      }
      return properties.getProperty(key);
    }

    public static void main(String[] args) {
      System.out.println("static.picture.address1>>>" + ReadPropertiesUtils2.getValue("static.picture.address1"));
      System.out.println("static.picture.address2>>>" + ReadPropertiesUtils2.getValue("static.picture.address2"));
    }
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Springboot整合MongoDB的Docker开发教程全解

    Springboot整合MongoDB的Docker开发教程全解

    这篇文章主要介绍了Springboot整合MongoDB的Docker开发,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值 ,需要的朋友可以参考下
    2020-07-07
  • Spring简明分析Bean作用域

    Spring简明分析Bean作用域

    scope用来声明容器中的对象所应该处的限定场景或者说该对象的存活时间,即容器在对象进入其 相应的scope之前,生成并装配这些对象,在该对象不再处于这些scope的限定之后,容器通常会销毁这些对象,这篇文章主要介绍了Spring中的Bean作用域,需要的朋友可以参考下
    2022-07-07
  • Arrays.asList方法总结

    Arrays.asList方法总结

    本文主要对Arrays.asList方法进行总结。具有很好的参考价值,下面跟着小编一起来看下吧
    2017-02-02
  • java读取文件和写入文件的方式(简单实例)

    java读取文件和写入文件的方式(简单实例)

    下面小编就为大家带来一篇java读取文件和写入文件的方式(简单实例)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-10-10
  • Spring MVC文件请求处理MultipartResolver详解

    Spring MVC文件请求处理MultipartResolver详解

    这篇文章主要介绍了Spring MVC文件请求处理详解:MultipartResolver,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-11-11
  • Java实现两人五子棋游戏(四) 落子动作的实现

    Java实现两人五子棋游戏(四) 落子动作的实现

    这篇文章主要为大家详细介绍了Java实现两人五子棋游戏,落子动作的实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-03-03
  • java实现连接mysql数据库单元测试查询数据的实例代码

    java实现连接mysql数据库单元测试查询数据的实例代码

    下面小编就为大家带来一篇java实现连接mysql数据库单元测试查询数据的实例代码。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-10-10
  • 关于@SpringBootApplication与@SpringBootTest的区别及用法

    关于@SpringBootApplication与@SpringBootTest的区别及用法

    这篇文章主要介绍了关于@SpringBootApplication与@SpringBootTest的区别及用法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-01-01
  • Java深入浅出理解快速排序以及优化方式

    Java深入浅出理解快速排序以及优化方式

    快速排序由于排序效率在同为O(N*logN)的几种排序方法中效率较高,因此经常被采用,再加上快速排序思想----分治法也确实实用,因此很多软件公司的笔试面试,包括像腾讯,微软等知名IT公司都喜欢考这个,还有大大小的程序方面的考试如软考,考研中也常常出现快速排序的身影
    2021-11-11
  • JAVA进阶之HashMap底层实现解析

    JAVA进阶之HashMap底层实现解析

    Hashmap是java面试中经常遇到的面试题,大部分都会问其底层原理与实现,为了能够温故而知新,特地写了这篇文章,以便时时学习
    2021-11-11

最新评论