Before we know that the private void parseConfiguration(XNode root) method is called during the configuration creation process, there is a pluginElement(root.evalNode("plugins")); method, this is the plugin that reads the configuration;
private void pluginElement(XNode parent) throws Exception { if (parent != null) { for (XNode child : parent.getChildren()) { String interceptor = child.getStringAttribute("interceptor"); Properties properties = child.getChildrenAsProperties(); Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance(); interceptorInstance.setProperties(properties); configuration.addInterceptor(interceptorInstance); } } }
See this sentence:
Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
Yes, this is the plug-in that reads the plug-in node and configuration parameters during the initialization of the mybatis context, and generates a plug-in instance through reflection technology;
configuration.addInterceptor(interceptorInstance);
Put the plugin into the configuration and follow up:
public class InterceptorChain { private final List<Interceptor> interceptors = new ArrayList<Interceptor>(); public Object pluginAll(Object target) { for (Interceptor interceptor : interceptors) { target = interceptor.plugin(target); } return target; } public void addInterceptor(Interceptor interceptor) { interceptors.add(interceptor); } public List<Interceptor> getInterceptors() { return Collections.unmodifiableList(interceptors); } }
Finally, the plugin is saved in a list object and waiting to be called.
There is a plug-in interface that needs to be said, that is Interceptor, enter it:
public interface Interceptor { Object intercept(Invocation invocation) throws Throwable; Object plugin(Object target); void setProperties(Properties properties); }
There are only three methods in this interface, so let's introduce the function of each method:
1) The intercept() method is the core method of the plug-in, which directly overwrites the original method of the intercepted object;
2) The plugin() method is to generate a proxy object for the intercepted object and return it; to explain more here, mybatis provides the wrap static method in org.apache.ibatis.plugin.Plugin to generate a proxy object;
3) setProperties() allows all parameters to be configured in the plugin element;
We will call when we get the four directions
public Object pluginAll(Object target) { for (Interceptor interceptor : interceptors) { target = interceptor.plugin(target); } return target; }
The plugin() here is the method 2) in the interface, the purpose is to generate a proxy object;