Detailed Explanation of Mybatis Properties Configuration Priority

  • 2021-10-25 06:59:43
  • OfStack

Properties configuration mode

Mybatis provides three configurations:

property sub-element in properties element properties Configuration File Program parameter transfer

Configure priority level

The attribute specified in the body of the properties element is read first Properties Configured in properties Configuration File The way of passing by parameters

Therefore, attributes passed through parameters have the highest priority, followed by properties configuration files, and attributes specified in properties element bodies have the lowest priority.

Therefore, it is necessary to pay attention in production. The best way is not to mix them. It is recommended to use properties configuration file form.

Mybatis properties Properties

These properties are externally configurable and dynamically replaceable

It can be configured in a typical Java properties file or passed through child elements of an properties element.

For example:


<span style="font-size:14px;"><properties resource="org/mybatis/example/config.properties">
  <property name="username" value="dev_user"/>
  <property name="password" value="F2Fa3!33TYyg"/>
</properties></span>

The properties can be used throughout the configuration file to replace property values that need to be dynamically configured.

For example:


<dataSource type="POOLED">
  <property name="driver" value="${driver}"/>
  <property name="url" value="${url}"/>
  <property name="username" value="${username}"/>
  <property name="password" value="${password}"/>
</dataSource>

username and password in this example will be replaced by the corresponding values set in the properties element.

The driver and url attributes will be replaced with the corresponding values in the config. properties file.

This provides many flexible choices for configuration.

If the property is configured in more than 1 place

Then MyBatis will be loaded in the following order:

The attributes specified in the body of an properties element are read first. Then read the properties file under the ClassPath based on the resource attribute in the properties element or the path specified by the url attribute, and overwrite the read property with the same name. Finally, the property passed as a method parameter is read, and the read property with the same name is overwritten.

Therefore, the property passed through the method parameter has the highest priority, followed by the profile specified in the resource/url property, and the property specified in the properties property has the lowest priority.


Related articles: