spring读取properties和其余配置文件的几种方式

一、由于spring容器的一些机制,在读取配置文件进行数据库的配置等等是颇有必要的,因此咱们要考虑配置文件的的读取方式以及各个方式的实用性java

二、配置文件的读取方式我这里介绍2种,目的是掌握这2种就能够很好的应用了mysql

三、这里个人properies配置文件以下:spring

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/m_model?useUnicode=true&characterEncoding=utf8
username=root
password=root

四、第一种读取方式:一种采用bean的配置方式,一种是标签的形式sql

  1)bean的配置方式(推荐使用这种方式)数据库

  <bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <!-- 若是是单个文件能够按照注释的方式来配置 -->
        <!-- <property name="location" value="classpath:conf/spring-config.properties"/> -->
        <property name="locations">
            <array>
                <value>classpath:conf/spring-config.properties</value>
            </array>
        </property>
    </bean>
    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>

  2)标签的配置方式apache

   <context:property-placeholder location="classpath:conf/spring-config.properties"/>
    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>

问题:这里我遇到了读取配置处错的问题:编码

会出现乱码的状况,而后我找了一些处理方式
  (1)修改properties针对字符的配置url

url=jdbc:mysql\://localhost\:3306\/m_model?useUnicode=true&amp;characterEncoding=utf8

  (2)加入读取配置时进行文件编码spa

<context:property-placeholder location="classpath:conf/spring-config.properties" file-encoding="UTF-8"/>  

这两种方式我都试过了,目前还不知道什么缘由致使的乱码问题。有大神能够指教一下
指教!指教!指教!指教!指教!指教!指教!指教!指教!指教!指教!指教!指教!指教!指教!指教!指教!指教!指教!指教!指教!指教!指教!指教!3d

五、是用util:properties便签来实现的,这种方式就是单纯的来读取配置文件

<util:properties id="config" location="classpath:conf/spring-config.properties"/>
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="#{config.driver}"/>
        <property name="url" value="#{config.url}"/>
        <property name="username" value="#{config.username}"/>
        <property name="password" value="#{config.password}"/>
    </bean>
    

 注意:这里是采用#{id.属性}来实现具体的读取,上面是直接$(属性来实现的)

六、这两种方式是针对于xml配置xml赋值的方式来实现,在使用过程当中也可使用经过标签的方式给具体的java代码赋值,便于管理

@Value("#{config.username}")
private String userName;

这种方式也能够用来装配具体的属性,便于合理管理相关配置

相关文章
相关标签/搜索