• spring配置属性的两种方式


     spring配置属性有两种方式,第一种方式通过context命名空间中的property-placeholder标签

    <context:property-placeholder location="classpath:jdbctemplate/jdbc.properties" />

    第二种方式通过创建bean,对应类为PropertyPlaceholderConfigurer

      <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
      </bean>

    第一种方式精短易读,第二种方式更通用,不搞特权,各有各的好处.

    经过测试,这两种方式都是可以获取属性文件中的属性的.

    然而,却有一个这样的bug,至今不明其理.下面列出2个文件:

    文件1

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/test
    jdbc.username=root
    jdbc.password=haha

    使用这个文件的属性时,当然要用${jdbc.driver}这种形式

    文件2

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/test
    username=root
    password=haha

    context方式引入属性文件,无法与文件2搭配,但可以与文件1搭配

    bean方式引入属性文件,都可以搭配

    context与文件2搭配报错

    Exception in thread "main" org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Access denied for user 'weidiao'@'localhost' (using password: YES)
        at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:80)
        at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:390)
        at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:470)
        at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:480)
        at org.springframework.jdbc.core.JdbcTemplate.queryForList(JdbcTemplate.java:501)
        at jdbctemplate.UserDao.getAllUserNames(UserDao.java:31)
        at jdbctemplate.Main.main(Main.java:12)
    Caused by: java.sql.SQLException: Access denied for user 'weidiao'@'localhost' (using password: YES)
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:959)

     

  • 相关阅读:
    hdu 5053 the Sum of Cube
    [LeetCode] Word Pattern
    [LeetCode] Minimum Depth of Binary Tree
    [C++] std::vector
    [LeetCode] Count Binary Substrings
    [LeetCode] Degree of an Array
    [LeetCode] String to Integer (atoi)
    [LintCode] 比较字符串
    [LeetCode] Valid Parentheses
    [LeetCode] Perfect Number
  • 原文地址:https://www.cnblogs.com/weiyinfu/p/5591541.html
Copyright © 2020-2023  润新知