One of the functions of the interceptor is that we can intercept the calls of certain methods. We can choose to add some logic before and after the execution of these intercepted methods, or discard these intercepted methods and execute our own logic. .
For example, for the Executor of mybatis, there are several implementations: BatchExecutor, ReuseExecutor, SimpleExecutor and CachingExecutor. When the query methods of these Executor interfaces cannot When our requirements are met, we can build an interceptor to implement our own query method; interceptors are generally implemented dynamically using aop.
Interceptor principle
For mybatis, we can define our own interceptor through the interceptor interface. Interceptor interface definition:
1 2 3 4 5 6 7 |
|
The plugin method is mainly used to encapsulate the target object. Through this method, we can decide whether to intercept and then decide what kind of target object to return.
The intercept method is the method that is executed when intercepting. setProperties is mainly used to specify properties in the configuration file. This method will be executed when Configuration initializes the current Interceptor. There is a plugin class in mybatis, which includes the static method wrap. Through this method, it can be determined whether the object to be returned is the target. Objects or agents.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
|
Interceptor instance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
|
First mark this as an Interceptor with @Intercepts, and design the interception point through @Signatrue: the parameter type in the interceptor Executor interface is MappedStatement, The query method of Object, RowBounds and ResultHandler; the intercept method calls the proceed method of invocation to make the current method call normally.
Registration of interceptors
Registration of interceptors is carried out through the plugin element under the plugins element in the Mybatis configuration file. Mybatis is defined in the registration When using an interceptor, all properties under the corresponding interceptor will first be injected through the setProperties method of the Interceptor. Such as:
1 2 3 4 5 |
|
The above is the detailed content of mybatis interceptor. For more information, please follow other related articles on the PHP Chinese website!