Spring/Maven/MyBatis配置文件結合properties文件使用


使用properties文件也叫注入,比如把一些常用的配置項寫入到這個文件,然后在Spring的XML配置文件中使用EL表達式去獲取。

這種方式不只Spring可以使用,同樣MyBatis也可以使用,只不過加載的方式不一樣,但是獲取值同樣是EL表達式。具體的參考官方文檔。

properties語法參考:https://zh.wikipedia.org/wiki/.properties,注意轉移字符。

 

Spring:

本次使用的例子來自這章http://www.cnblogs.com/EasonJim/p/7055499.html,通過改造實現將數據庫連接信息全部使用properties去配置。

前提:

1、新建db.properties文件,加入如下配置:

jdbc.username=root
jdbc.password=root
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://127.0.0.1\:3306/test?useUnicode\=true&characterEncoding\=UTF-8&serverTimezone\=UTC

注意:在定義這些變量的時候,盡量避免一些系統變量,比如username,這個代表操作系統的用戶名。

2、在加載properties文件路徑上,使用的是classpath加通配符*去實現掃描項目的classes目錄下的文件來加載,不再是絕對路徑,具體的用法參考:http://www.cnblogs.com/EasonJim/p/6709314.html

下面將列舉加載方式:

提示:在獲取值時,通常可以為其設置默認值,比如${timeout:100}

一、<context:property-placeholder />

1、在配置Spring的Bean文件時,比如引入頭聲明,如下所示:

...
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
...

2、Bean配置文件加入:

<context:property-placeholder ignore-unresolvable="true" location="classpath:db.properties" />

3、獲取變量:

    <!--采用DBCP連接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

二、<util:properties />

1、在配置Spring的Bean文件時,比如引入頭聲明,如下所示:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

2、Bean配置文件加入:

<util:properties id="db" location="classpath:db.properties"/>

3、獲取變量:

    <!--采用DBCP連接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="#{db['jdbc.driver']}" />
        <property name="url" value="#{db['jdbc.url']}" />
        <property name="username" value="#{db['jdbc.username']}" />
        <property name="password" value="#{db['jdbc.password']}" />
    </bean>

三、通過代碼注入實現代碼上可以獲取這些變量(@Value)

1、Bean配置文件加入:

    <!-- 使用注解注入properties中的值 -->
    <bean id="config" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath:db.properties</value>
            </list>
        </property>
        <!-- 設置編碼格式 -->
        <property name="fileEncoding" value="UTF-8"></property>
    </bean>

2、在需要測試的類中寫入如下代碼,但是這個類必須是通過Bean注入過的,做直接的使用就是MVC的Controller。

package com.jsoft.testmybatis.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.jsoft.testmybatis.inter.IUserOperation;
import com.jsoft.testmybatis.models.Article;

@Controller
@RequestMapping("/article")
public class UserController {
    
    @Value("#{config['jdbc.username']}") private String userName; @Value("#{config['jdbc.password']}") private String password; @Value("#{config['jdbc.url']}") private String url; @Value("#{config['jdbc.driver']}") private String driver;
    
    @Autowired
    IUserOperation userMapper;

    @RequestMapping("/list")
    public ModelAndView listall(HttpServletRequest request,HttpServletResponse response){
        
        System.out.println("測試:"+this.userName+"-"+this.password+"-"+this.url+"-"+this.driver);
        
        List<Article> articles=userMapper.getUserArticles(1); 
        ModelAndView mav=new ModelAndView("/article/list");
        mav.addObject("articles",articles);
        return mav;
    }
}

3、另一種Bean實現,定義

復制代碼
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <array>
            <value>classpath:db.properties</value>
        </array>
    </property>
</bean>
復制代碼

4、使用@value注解獲取配置文件的值

@Value("${isenable}")
private Boolean isEnable;

 

Maven:

在Maven使用很有幫助,比如多模塊項目時,在Parent模塊上定一個總的屬性,每個模塊引入之后,到時需要修改也只是一處地方。

一、直接在POM中使用properties定義屬性

1、POM

    <!-- 項目屬性 -->
    <properties>
        <!-- main version setting -->
        <servlet.version>3.1.0</servlet.version>
    </properties>

2、使用:

        <!-- Servlet Library -->
        <!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>

二、如果對於引入文件基本是無解,只能在POM中定義。

 

MyBatis:

一、通過properties節點引入:

1、在MyBatis配置文件下引入:

...
<configuration>

    <!-- 引入properties配置文件 --> <properties resource="config.properties" />
...

2、使用:

    <!-- 配置環境 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>

 

測試工程:https://github.com/easonjim/5_java_example/tree/master/springtest/test21

 

參考:

http://www.cnblogs.com/BensonHe/p/3963940.html

http://blog.csdn.net/csujiangyu/article/details/50945486

http://xitongjiagoushi.blog.51cto.com/9975742/1659051/

http://825635381.iteye.com/blog/2196906

http://www.cnblogs.com/atliwen/p/5729670.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM