简体   繁体   中英

Ibatis load properties file based on environment variables

I'm trying to refactor an old application in order to build it once and deploy it everywhere. The issue that I'm facing like now is the properties file, taken by ibatis could not understand any placeholder for any environment variables. So theoretically I would need something like this:

<properties url="file:///${sys:catalina.home}/tools/apache-tomcat-8.5.70/data/tomapps/proj.properties"/>

Something that is in similar fashion like log4j2 understands:

<File name="LogToFile" fileName="${sys:catalina.home}/logs/proj.log">

Ok, so this is the context. log4j2 understand this, but ibatis not at all.. Not even relative path from linux: ~/specific/path

So I've took a look over this one: Using Environment variables in Mybatis properties file , which is a good solution if you want to switch everything from xml style to java.

But in my case this is an old applications with many mappers defined in xml files, and I prefer to leave as it is.

After some days of back and forth, it seems that I found a solution that is working with leaving all the mappers in xml files, which was great!

First thing first was to DELETE the properties line(the one which was loading all the ibatis configs) from my sqlMapConfig.xml.

And from Java, instead of loading the config like this:

Reader reader = Resources.getResourceAsReader("/resources/sqlMapConfig.xml");
sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);

this change managed to load properties file from an external relative path:

   Reader reader = Resources.getResourceAsReader("/resources/sqlMapConfig.xml");
sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader, loadProperties());

where loadProperties() method looks like this:

private static Properties loadProperties() throws IOException {
if (configProps == null) {
    String catalinaHome = System.getProperty("catalina.home");
    String url = "file:///${sys:catalina.home}/data/tomapps/proj.properties".replace("${sys:catalina.home}", catalinaHome);
    configProps = new Properties();
    try (InputStream is = new URL(url).openStream()) {
        configProps.load(is);
    }
}
return configProps;

}

So this helped me trick ibatis in understanding ${sys:catalina.home} . Hope this will help you too. Happy codding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM