In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the SpringBoot integration of Mybatis custom interceptor does not work how to do, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor with you to understand.
SpringBoot Integration Mybatis Custom interceptor does not work
How the Mybatis plug-in takes effect:
1. The original read mybatis-config.xml file
This approach is independent of Spring and creates a plug-in object in the form of reflection, where the org.apache.ibatis.plugin.Interceptor#setProperties method is executed to read the configuration parameters.
Mybatis: mapper-locations: classpath*:/mapping/*.xml type-aliases-package: com.tellme.pojo # read the globally configured address config-location: classpath:mybatis-config.xml
Configure the global configuration of mybatis under the resource directory:
two。 Integration with SpringBoot container
Many solutions on the Internet say: add @ Component annotation to mybatis custom interceptor and it will take effect. But I put the custom interceptor into the Spring container, and the custom interceptor failed.
Then we found the article that the mybatis interceptor failed after springboot configured multiple data sources, saying that the custom configuration of the data source caused the interceptor failure.
2.1Automated loading of mybatis
Source location: org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration
@ Configuration@ConditionalOnClass ({SqlSessionFactory.class, SqlSessionFactoryBean.class}) @ ConditionalOnBean (DataSource.class) @ EnableConfigurationProperties (MybatisProperties.class) @ AutoConfigureAfter (DataSourceAutoConfiguration.class) public class MybatisAutoConfiguration {private static Log log = LogFactory.getLog (MybatisAutoConfiguration.class); @ Autowired private MybatisProperties properties; / / relies on the Interceptor interceptor @ Autowired (required = false) private Interceptor [] interceptors;. @ Bean @ ConditionalOnMissingBean public SqlSessionFactory sqlSessionFactory (DataSource dataSource) throws Exception {SqlSessionFactoryBean factory = new SqlSessionFactoryBean () Factory.setDataSource (dataSource); factory.setVfs (SpringBootVFS.class); if (StringUtils.hasText (this.properties.getConfigLocation () {factory.setConfigLocation (this.resourceLoader.getResource (this.properties.getConfigLocation ();} factory.setConfiguration (properties.getConfiguration ()); / / manually put into the setPlugins method. If (! ObjectUtils.isEmpty (this.interceptors)) {factory.setPlugins (this.interceptors);} if (this.databaseIdProvider! = null) {factory.setDatabaseIdProvider (this.databaseIdProvider);} if (StringUtils.hasLength (this.properties.getTypeAliasesPackage () {factory.setTypeAliasesPackage (this.properties.getTypeAliasesPackage ());} if (StringUtils.hasLength (this.properties.getTypeHandlersPackage () {factory.setTypeHandlersPackage (this.properties.getTypeHandlersPackage ()) } if (! ObjectUtils.isEmpty (this.properties.resolveMapperLocations () {factory.setMapperLocations (this.properties.resolveMapperLocations ());} return factory.getObject ();}.}
The above source code: the Interceptor [] array is automatically injected (we just need to put the custom interceptor object of mybatis into the Spring container). Then put it into the sqlSessionFactory.
However, although the sqlSessionFactory class is customized in the project, factory.setPlugins (this.interceptors); is not set. Causes even if the custom interceptor is put into the Spring container, it does not take effect.
As a solution, you need to manually modify the custom sqlSessionFactory class.
3. Put the Spring container in the mybatis-config.xml configuration
In this case, the mybatis custom interceptor is executed twice. That is, interceptors configured in mybatis-config.xml will create interceptors through reflection, and interceptors placed in the Spring container will also be initialized.
Source location: org.mybatis.spring.SqlSessionFactoryBean#buildSqlSessionFactory
Protected SqlSessionFactory buildSqlSessionFactory () throws IOException {Configuration configuration;... Read the plugins in the property, that is, set by org.mybatis.spring.SqlSessionFactoryBean#setPlugins. If (! isEmpty (this.plugins)) {for (Interceptor plugin: this.plugins) {configuration.addInterceptor (plugin); if (LOGGER.isDebugEnabled ()) {LOGGER.debug ("Registered plugin:'" + plugin + "");}. Parsing xml configuration (creating interceptor objects through reflection) if (xmlConfigBuilder! = null) {try {xmlConfigBuilder.parse (); if (LOGGER.isDebugEnabled ()) {LOGGER.debug ("Parsed configuration file:'" + this.configLocation + "'") } catch (Exception ex) {throw new NestedIOException ("Failed to parse config resource:" + this.configLocation, ex);} finally {ErrorContext.instance (). Reset ();}} return this.sqlSessionFactoryBuilder.build (configuration);}
Will eventually be executed to:
Private void pluginElement (XNode parent) throws Exception {if (parent! = null) {for (XNode child: parent.getChildren ()) {String interceptor = child.getStringAttribute ("interceptor"); Properties properties = child.getChildrenAsProperties (); / / reflects the plug-in that creates mybatis. Interceptor interceptorInstance = (Interceptor) resolveClass (interceptor). NewInstance (); interceptorInstance.setProperties (properties); configuration.addInterceptor (interceptorInstance);}} SpringBoot Custom Mybatis interceptor
During the development process, you often need to customize the sql to be executed, such as paging, counting, and so on. With the powerful mechanism provided by MyBatis, using a plug-in is as simple as implementing the Interceptor interface and specifying the method signature you want to intercept.
@ Intercepts ({@ Signature (type = Executor.class,method = "query", args = {MappedStatement.class,Object.class, RowBounds.class,ResultHandler.class}) public class MyPageInterceptor implements Interceptor {private static final Logger logger= LoggerFactory.getLogger (MyPageInterceptor.class); @ Override public Object intercept (Invocation invocation) throws Throwable {logger.warn (invocation.toString ()); return invocation.proceed () } @ Override public Object plugin (Object o) {return Plugin.wrap (odepartment this);} @ Override public void setProperties (Properties properties) {logger.warn (properties.toString ());}}
My configuration
Mybatis: type-aliases-package: me.zingon.pagehelper.model mapper-locations: classpath:mapper/*.xml configuration: map-underscore-to-camel-case: true default-fetch-size: 100 default-statement-timeout: 30
There are three ways to add this interceptor to mybatis in springboot. The first two methods do not automatically call the setProperties method of the custom interceptor when you start the project.
First kind
Directly add a @ Component annotation to the custom interceptor. When sql is called, the result is as follows. You can see that the interceptor works, but the setProperties method is not automatically called at startup.
The second kind
Add an interceptor to the configuration class, the result of this method is the same as above, and the setProperties method is not automatically called.
@ Configurationpublic class MybatisConfig {@ Bean ConfigurationCustomizer mybatisConfigurationCustomizer () {return new ConfigurationCustomizer () {@ Override public void customize (org.apache.ibatis.session.Configuration configuration) {configuration.addInterceptor (new MyPageInterceptor ());};}} the third kind
This method is similar to the previous configuration method. Specify the xml configuration file of mybatis in the yml configuration file. Note that the config-location property and the configuration property cannot be specified at the same time.
Mybatis: config-location: classpath:mybatis.xml type-aliases-package: me.zingon.pagehelper.model mapper-locations: classpath:mapper/*.xml
As you can see, setProperties is called automatically when the project is started
The first two methods can initialize the required parameters directly through the @ Value annotation when initializing the custom interceptor.
Thank you for reading this article carefully. I hope the article "what if the SpringBoot Integration Mybatis Custom interceptor doesn't work" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.