Using Environment variables in Mybatis properties file

3.2k Views Asked by At

I am using mybatis to connect to database and i have stored some schema information in external properties file. I have kept this property file somewhere on my disk and referring it in my config.xml like below

In Config.xml

<properties url="file:///E:/mybatis/sqlmapconfig.properties" />

In my sqlmapconfig.properties file

schema=test_schema

I do want to make this path configurable by user, meaning users can set an environment like "MyBatis.Config" with value as "E:/mybatis". so that you can refer it in the config.xml file as something like below

<properties url="file:///${env.MyBatis.Config}/sqlmapconfig.properties"/>

I have tried the above snippet but did not pick the property file. Anybody has idea on how we can use system or environment variable in property files in Mybatis context.

1

There are 1 best solutions below

0
On BEST ANSWER

MyBatis does not expand environment variables like that.
You may have to build Configuration in Java code.
See this doc for the basics.

Then call configuration.setVariables() to set the loaded Properties.

String envVar = System.getenv("MyBatis.Config");
String url = "file:///${env.MyBatis.Config}/sqlmapconfig.properties"
  .replace("${env.MyBatis.Config}", envVar);
Properties props = new Properties();
try (InputStream propStream = new URL(url).openStream()) {
  props.load(propStream);
}
configuration.setVariables(props);
configuration.addMapper(YourMapper.class);

Note that mappers must be added after setting variables.