MyBatis | 設定ファイル | 外部プロパティファイルを読み込む

コード

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <properties resource="hoge.properties">
    <property name="hoge" value="property tag"/>
    <property name="fuga" value="property tag"/>
    <property name="piyo" value="property tag"/>
  </properties>
</configuration>

hoge.properties

fuga=property file
piyo=property file

Main.java

package sample.mybatis;

import java.io.InputStream;
import java.util.Properties;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class Main {

    public static void main(String[] args) throws Exception {
        try (InputStream in = Main.class.getResourceAsStream("/mybatis-config.xml")) {
            Properties prop = new Properties();
            prop.put("piyo", "Properties Class");

            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in, prop);
            Properties properties = factory.getConfiguration().getVariables();

            properties.forEach((key, value) -> {
                System.out.printf("%s=%s%n", key, value);
            });
        }
    }
}

実行結果

hoge=property tag
fuga=property file
piyo=Properties Class

説明

  • プロパティは次の場所で定義できる。
    • <properties> タグの中に <property> タグを定義する。
    • <properties> タグで読み込むプロパティファイルを定義する。
    • SqlSessionFactory を作成するときに Properties インスタンスを渡す。
  • 各定義は上から下の順に読み込まれ、後から読み込まれた値が前の値を上書きする。
  • <properties> タグで別ファイルを読み込む場合、resource 属性にリソースファイルを指定するか、url 属性に URL を指定してファイルを読み込める。
    • url 属性で指定する場合は、file:///C:/foo/bar/hoge.properties のように指定する。
  • 読み込んだプロパティは ${...} 形式で参照できる。