Mybatis插件擴(kuò)展及與Spring整合原理分析
前言
前面幾篇文章分析了Mybatis的核心原理,但模塊較多,沒有一一分析,更多的需要讀者自己下來研究。不過Mybatis的插件擴(kuò)展機(jī)制還是非常重要的,像PageHelper就是一個(gè)擴(kuò)展插件,熟悉其擴(kuò)展原理,才能更好的針對我們的業(yè)務(wù)作出更合適的擴(kuò)展。另外,現(xiàn)在Mybatis都是和Spring/SpringBoot一起使用,那么Mybatis又是如何與它們進(jìn)行整合的呢?一切答案盡在本文之中。
正文
插件擴(kuò)展
1. Interceptor核心實(shí)現(xiàn)原理
熟悉Mybatis配置的都知道,在xml配置中我們可以配置如下節(jié)點(diǎn):
<plugins> <plugin interceptor="org.apache.ibatis.builder.ExamplePlugin"> <property name="pluginProperty" value="100"/> </plugin> </plugins>
這個(gè)就是插件的配置,那么自然而然的這個(gè)節(jié)點(diǎn)就會在解析xml的時(shí)候進(jìn)行解析,并將其添加到Configuration中。細(xì)心的讀者應(yīng)該還記得下面這段代碼,在XMLConfigBuilderl類中:
private void parseConfiguration(XNode root) { try { //issue #117 read properties first //解析<properties>節(jié)點(diǎn) propertiesElement(root.evalNode("properties")); //解析<settings>節(jié)點(diǎn) Properties settings = settingsAsProperties(root.evalNode("settings")); loadCustomVfs(settings); //解析<typeAliases>節(jié)點(diǎn) typeAliasesElement(root.evalNode("typeAliases")); //解析<plugins>節(jié)點(diǎn) pluginElement(root.evalNode("plugins")); //解析<objectFactory>節(jié)點(diǎn) objectFactoryElement(root.evalNode("objectFactory")); //解析<objectWrapperFactory>節(jié)點(diǎn) objectWrapperFactoryElement(root.evalNode("objectWrapperFactory")); //解析<reflectorFactory>節(jié)點(diǎn) reflectorFactoryElement(root.evalNode("reflectorFactory")); settingsElement(settings);//將settings填充到configuration // read it after objectFactory and objectWrapperFactory issue #631 //解析<environments>節(jié)點(diǎn) environmentsElement(root.evalNode("environments")); //解析<databaseIdProvider>節(jié)點(diǎn) databaseIdProviderElement(root.evalNode("databaseIdProvider")); //解析<typeHandlers>節(jié)點(diǎn) typeHandlerElement(root.evalNode("typeHandlers")); //解析<mappers>節(jié)點(diǎn) mapperElement(root.evalNode("mappers")); } catch (Exception e) { throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e); } }
其中pluginElement就是解析插件節(jié)點(diǎn)的:
private void pluginElement(XNode parent) throws Exception { if (parent != null) { //遍歷所有的插件配置 for (XNode child : parent.getChildren()) { //獲取插件的類名 String interceptor = child.getStringAttribute("interceptor"); //獲取插件的配置 Properties properties = child.getChildrenAsProperties(); //實(shí)例化插件對象 Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance(); //設(shè)置插件屬性 interceptorInstance.setProperties(properties); //將插件添加到configuration對象,底層使用list保存所有的插件并記錄順序 configuration.addInterceptor(interceptorInstance); } } }
從上面可以看到,就是根據(jù)配置實(shí)例化為Interceptor對象,并添加到InterceptorChain中,該類的對象被Configuration持有。Interceptor包含三個(gè)方法:
//執(zhí)行攔截邏輯的方法 Object intercept(Invocation invocation) throws Throwable; //target是被攔截的對象,它的作用就是給被攔截的對象生成一個(gè)代理對象 Object plugin(Object target); //讀取在plugin中設(shè)置的參數(shù) void setProperties(Properties properties);
而InterceptorChain只是保存了所有的Interceptor,并提供方法給客戶端調(diào)用,使得所有的Interceptor生成代理對象:
public class InterceptorChain { private final List<Interceptor> interceptors = new ArrayList<>(); 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); } }
可以看到pluginAll就是循環(huán)去調(diào)用了Interceptor的plugin方法,而該方法的實(shí)現(xiàn)一般是通過Plugin.wrap去生成代理對象:
public static Object wrap(Object target, Interceptor interceptor) { //解析Interceptor上@Intercepts注解得到的signature信息 Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor); Class<?> type = target.getClass();//獲取目標(biāo)對象的類型 Class<?>[] interfaces = getAllInterfaces(type, signatureMap);//獲取目標(biāo)對象實(shí)現(xiàn)的接口 if (interfaces.length > 0) { //使用jdk的方式創(chuàng)建動態(tài)代理 return Proxy.newProxyInstance( type.getClassLoader(), interfaces, new Plugin(target, interceptor, signatureMap)); } return target; }
其中g(shù)etSignatureMap就是將@Intercepts注解中的value值解析并緩存起來,該注解的值是@Signature類型的數(shù)組,而這個(gè)注解可以定義class類型、方法、參數(shù),即攔截器的定位。而getAllInterfaces就是獲取要被代理的接口,然后通過JDK動態(tài)代理創(chuàng)建代理對象,可以看到InvocationHandler就是Plugin類,所以直接看invoke方法,最終就是調(diào)用interceptor.intercept方法:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { //獲取當(dāng)前接口可以被攔截的方法 Set<Method> methods = signatureMap.get(method.getDeclaringClass()); if (methods != null && methods.contains(method)) {//如果當(dāng)前方法需要被攔截,則調(diào)用interceptor.intercept方法進(jìn)行攔截處理 return interceptor.intercept(new Invocation(target, method, args)); } //如果當(dāng)前方法不需要被攔截,則調(diào)用對象自身的方法 return method.invoke(target, args); } catch (Exception e) { throw ExceptionUtil.unwrapThrowable(e); } }
這里的插件實(shí)現(xiàn)思路是通用的,即這個(gè)interceptor我們可以用來擴(kuò)展任何對象的任何方法,比如對Map的get進(jìn)行攔截,可像下面這樣實(shí)現(xiàn):
@Intercepts({ @Signature(type = Map.class, method = "get", args = {Object.class})}) public static class AlwaysMapPlugin implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { return "Always"; } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { } }
然后在使用Map時(shí)先用插件對其包裝,這樣拿到的就是Map的代理對象。
Map map = new HashMap(); map = (Map) new AlwaysMapPlugin().plugin(map);
2. Mybatis的攔截增強(qiáng)
因?yàn)槲覀兛梢詫ybatis擴(kuò)展任意多個(gè)的插件,所以它使用InterceptorChain對象來保存所有的插件,這是責(zé)任鏈模式的實(shí)現(xiàn)。那么Mybatis到底會攔截哪些對象和哪些方法呢?回憶上篇文章我們就可以發(fā)現(xiàn)Mybatis只會對以下4個(gè)對象進(jìn)行攔截:
Executor:
public Executor newExecutor(Transaction transaction, ExecutorType executorType) { ......省略 //通過interceptorChain遍歷所有的插件為executor增強(qiáng),添加插件的功能 executor = (Executor) interceptorChain.pluginAll(executor); return executor; }
StatementHandler
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) { //創(chuàng)建RoutingStatementHandler對象,實(shí)際由statmentType來指定真實(shí)的StatementHandler來實(shí)現(xiàn) StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql); statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler); return statementHandler; }
ParameterHandler
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) { ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql); parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler); return parameterHandler; }
ResultSetHandler
public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler, ResultHandler resultHandler, BoundSql boundSql) { ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds); resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler); return resultSetHandler; }
而具體要攔截哪些對象和哪些方法則是由@Intercepts和@Signature指定的。
以上就是Mybatis擴(kuò)展插件的實(shí)現(xiàn)機(jī)制,讀者可據(jù)此自行分析下PageHelper的實(shí)現(xiàn)原理。另外需要注意,我們在進(jìn)行自定義插件開發(fā)時(shí),尤其要謹(jǐn)慎。因?yàn)橹苯雨P(guān)系到操作數(shù)據(jù)庫,如果對插件的實(shí)現(xiàn)原理不透徹,很有可能引發(fā)難以估量的后果。
Mybatis與Spring整合原理
前面的示例都是單獨(dú)使用Mybatis,可以看到需要?jiǎng)?chuàng)建SqlSessionFactory和SqlSession對象,然后通過SqlSession去創(chuàng)建Mapper接口的代理對象,所以在與Spring整合時(shí),顯而易見的,我們就需要考慮以下幾點(diǎn):
- 什么時(shí)候創(chuàng)建以及怎么創(chuàng)建SqlSessionFactory和SqlSession?
- 什么時(shí)候創(chuàng)建以及怎么創(chuàng)建代理對象?
- 如何將Mybatis的代理對象注入到IOC容器中?
- Mybatis怎么保證和Spring在同一個(gè)事務(wù)中并且使用的是同一個(gè)連接?
那么如何實(shí)現(xiàn)以上幾點(diǎn)呢?下文基于mybatis-spring-1.3.3版本分析。
1. SqlSessionFactory的創(chuàng)建
熟悉Spring源碼的(如果不熟悉,可以閱讀我之前的Spring系列源碼)都知道Spring最重要的那些擴(kuò)展點(diǎn):
- BeanDefinitionRegistryPostProcessor:Bean實(shí)例化前調(diào)用
- BeanFactoryPostProcessor:Bean實(shí)例化前調(diào)用
- InitializingBean:Bean實(shí)例化后調(diào)用
- FactoryBean:實(shí)現(xiàn)該接口代替Spring管理一些特殊的Bean
其它還有很多,以上列舉出來的就是Mybatis集成Spring所用到的擴(kuò)展點(diǎn)。首先我們需要實(shí)例化SqlSessionFactory,而實(shí)例化該對象在Mybatis里實(shí)際上就是去解析一大堆配置并封裝到該對象中,所以我們不能簡單的使用<bean>標(biāo)簽來配置,為此Mybatis實(shí)現(xiàn)了一個(gè)類SqlSessionFactoryBean(這個(gè)類我們在以前使用整合包時(shí)都會配置),之前XML中的配置都以屬性的方式放入到了該類中:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="com.enjoylearning.mybatis.entity" /> <property name="mapperLocations" value="classpath:sqlmapper/*.xml" /> </bean>
進(jìn)入這個(gè)類,我們可以看到它實(shí)現(xiàn)了InitializingBean和FactoryBean接口,實(shí)現(xiàn)第一個(gè)接口的作用就是在該類實(shí)例化后立即去執(zhí)行配置解析的階段:
public void afterPropertiesSet() throws Exception { notNull(dataSource, "Property 'dataSource' is required"); notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required"); state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null), "Property 'configuration' and 'configLocation' can not specified with together"); this.sqlSessionFactory = buildSqlSessionFactory(); }
具體的解析就在buildSqlSessionFactory方法中,這個(gè)方法比較長,但不復(fù)雜,這里就不貼代碼了。而實(shí)現(xiàn)第二接口的作用就在于Spring獲取該類實(shí)例時(shí)實(shí)際上會通過getObject方法返回SqlSessionFactory的實(shí)例,通過這兩個(gè)接口就完成了SqlSessionFactory的實(shí)例化。
2. 掃描Mapper并創(chuàng)建代理對象
在整合之后我們除了要配置SqlSessionFactoryBean外,還要配置一個(gè)類:
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.enjoylearning.mybatis.mapper" /> </bean>
這個(gè)類的作用就是用來掃描Mapper接口的,并且這個(gè)類實(shí)現(xiàn)了BeanDefinitionRegistryPostProcessor和InitializingBean,這里實(shí)現(xiàn)第二個(gè)接口的作用主要是校驗(yàn)有沒有配置待掃描包的路徑:
public void afterPropertiesSet() throws Exception { notNull(this.basePackage, "Property 'basePackage' is required"); }
主要看到postProcessBeanDefinitionRegistry方法:
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) { if (this.processPropertyPlaceHolders) { processPropertyPlaceHolders(); } ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry); scanner.setAddToConfig(this.addToConfig); scanner.setAnnotationClass(this.annotationClass); scanner.setMarkerInterface(this.markerInterface); scanner.setSqlSessionFactory(this.sqlSessionFactory); scanner.setSqlSessionTemplate(this.sqlSessionTemplate); scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName); scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName); scanner.setResourceLoader(this.applicationContext); scanner.setBeanNameGenerator(this.nameGenerator); scanner.registerFilters(); scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS)); }
這里創(chuàng)建了一個(gè)掃描類,而這個(gè)掃描類是繼承自Spring的ClassPathBeanDefinitionScanner,也就是會將掃描到的類封裝為BeanDefinition注冊到IOC容器中去:
public int scan(String... basePackages) { int beanCountAtScanStart = this.registry.getBeanDefinitionCount(); doScan(basePackages); // Register annotation config processors, if necessary. if (this.includeAnnotationConfig) { AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry); } return (this.registry.getBeanDefinitionCount() - beanCountAtScanStart); } public Set<BeanDefinitionHolder> doScan(String... basePackages) { Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages); if (beanDefinitions.isEmpty()) { logger.warn("No MyBatis mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration."); } else { processBeanDefinitions(beanDefinitions); } return beanDefinitions; } private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) { GenericBeanDefinition definition; for (BeanDefinitionHolder holder : beanDefinitions) { definition = (GenericBeanDefinition) holder.getBeanDefinition(); if (logger.isDebugEnabled()) { logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName() + "' and '" + definition.getBeanClassName() + "' mapperInterface"); } // the mapper interface is the original class of the bean // but, the actual class of the bean is MapperFactoryBean definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); // issue #59 definition.setBeanClass(this.mapperFactoryBean.getClass()); definition.getPropertyValues().add("addToConfig", this.addToConfig); boolean explicitFactoryUsed = false; if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) { definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(this.sqlSessionFactoryBeanName)); explicitFactoryUsed = true; } else if (this.sqlSessionFactory != null) { definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory); explicitFactoryUsed = true; } if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) { if (explicitFactoryUsed) { logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored."); } definition.getPropertyValues().add("sqlSessionTemplate", new RuntimeBeanReference(this.sqlSessionTemplateBeanName)); explicitFactoryUsed = true; } else if (this.sqlSessionTemplate != null) { if (explicitFactoryUsed) { logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored."); } definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate); explicitFactoryUsed = true; } if (!explicitFactoryUsed) { if (logger.isDebugEnabled()) { logger.debug("Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'."); } definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); } } }
你可能會好奇,在哪里生成的代理對象?只是將Mapper接口注入到IOC有什么用呢?其實(shí)關(guān)鍵代碼就在definition.setBeanClass(this.mapperFactoryBean.getClass()),這句代碼的作用就是將每一個(gè)Mapper接口都轉(zhuǎn)為MapperFactoryBean類型。
為什么要這么轉(zhuǎn)呢?進(jìn)入這個(gè)類你會發(fā)現(xiàn)它也是實(shí)現(xiàn)了FactoryBean接口的,所以自然而然的又是利用它來創(chuàng)建代理實(shí)現(xiàn)類對象:
public T getObject() throws Exception { return getSqlSession().getMapper(this.mapperInterface); }
3. 如何整合Spring事務(wù)
Mybatis作為一個(gè)ORM框架,它是有自己的數(shù)據(jù)源和事務(wù)控制的,而Spring同樣也會配置這兩個(gè),那么怎么將它們整合到一起呢?而不是在Service類調(diào)用Mapper接口時(shí)就切換了數(shù)據(jù)源和連接,那樣肯定是不行的。
在使用Mybatis時(shí),我們可以在xml中配置TransactionFactory事務(wù)工廠類,不過一般都會使用默認(rèn)的JdbcTransactionFactory,而當(dāng)與Spring整合后,默認(rèn)的事務(wù)工廠類改為了SpringManagedTransactionFactory?;氐絊qlSessionFactoryBean讀取配置的方法,在該方法中有下面這樣一段代碼:
if (this.transactionFactory == null) { this.transactionFactory = new SpringManagedTransactionFactory(); } configuration.setEnvironment(new Environment(this.environment, this.transactionFactory, this.dataSource));
上面默認(rèn)創(chuàng)建了SpringManagedTransactionFactory,同時(shí)還將我們xml中ref屬性引用的dataSource添加到了Configuration中,這個(gè)工廠會創(chuàng)建下面這個(gè)事務(wù)控制對象:
public Transaction newTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit) { return new SpringManagedTransaction(dataSource); }
而這個(gè)方法是在DefaultSqlSessionFactory獲取SqlSession時(shí)會調(diào)用:
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) { Transaction tx = null; try { final Environment environment = configuration.getEnvironment(); final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment); tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit); final Executor executor = configuration.newExecutor(tx, execType); return new DefaultSqlSession(configuration, executor, autoCommit); } catch (Exception e) { closeTransaction(tx); // may have fetched a connection so lets call close() throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e); } finally { ErrorContext.instance().reset(); } }
這就保證使用的是同一個(gè)數(shù)據(jù)源對象,但是怎么保證拿到的是同一個(gè)連接和事務(wù)呢?關(guān)鍵就在于SpringManagedTransaction獲取連接是怎么實(shí)現(xiàn)的:
public Connection getConnection() throws SQLException { if (this.connection == null) { openConnection(); } return this.connection; } private void openConnection() throws SQLException { this.connection = DataSourceUtils.getConnection(this.dataSource); this.autoCommit = this.connection.getAutoCommit(); this.isConnectionTransactional = DataSourceUtils.isConnectionTransactional(this.connection, this.dataSource); if (LOGGER.isDebugEnabled()) { LOGGER.debug( "JDBC Connection [" + this.connection + "] will" + (this.isConnectionTransactional ? " " : " not ") + "be managed by Spring"); } }
這里委托給了DataSourceUtils獲取連接:
public static Connection getConnection(DataSource dataSource) throws CannotGetJdbcConnectionException { try { return doGetConnection(dataSource); } catch (SQLException ex) { throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", ex); } } public static Connection doGetConnection(DataSource dataSource) throws SQLException { Assert.notNull(dataSource, "No DataSource specified"); ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource); if (conHolder != null && (conHolder.hasConnection() || conHolder.isSynchronizedWithTransaction())) { conHolder.requested(); if (!conHolder.hasConnection()) { logger.debug("Fetching resumed JDBC Connection from DataSource"); conHolder.setConnection(dataSource.getConnection()); } return conHolder.getConnection(); } // Else we either got no holder or an empty thread-bound holder here. logger.debug("Fetching JDBC Connection from DataSource"); Connection con = dataSource.getConnection(); if (TransactionSynchronizationManager.isSynchronizationActive()) { logger.debug("Registering transaction synchronization for JDBC Connection"); // Use same Connection for further JDBC actions within the transaction. // Thread-bound object will get removed by synchronization at transaction completion. ConnectionHolder holderToUse = conHolder; if (holderToUse == null) { holderToUse = new ConnectionHolder(con); } else { holderToUse.setConnection(con); } holderToUse.requested(); TransactionSynchronizationManager.registerSynchronization( new ConnectionSynchronization(holderToUse, dataSource)); holderToUse.setSynchronizedWithTransaction(true); if (holderToUse != conHolder) { TransactionSynchronizationManager.bindResource(dataSource, holderToUse); } } return con; }
看到ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource)這段代碼相信熟悉Spring源碼的已經(jīng)知道了,這個(gè)我在分析Spring事務(wù)源碼時(shí)也講過,通過DataSource對象拿到當(dāng)前線程綁定的ConnectionHolder,這個(gè)對象是在Spring開啟事務(wù)的時(shí)候存進(jìn)去的。至此,關(guān)于Spring和Mybatis的整合原理我們就個(gè)搞清楚了,至于和SpringBoot的整合,讀者可自行分析。最后,我再分享一個(gè)小擴(kuò)展知識。
4. FactoryBean的擴(kuò)展知識
很多讀者可能不知道這個(gè)接口有什么作用,其實(shí)很簡單,當(dāng)我們有某個(gè)類由Spring實(shí)例化比較復(fù)雜,想要自己控制它的實(shí)例化時(shí),就可以實(shí)現(xiàn)該接口。而實(shí)現(xiàn)該接口的類首先會被實(shí)例化并放入一級緩存,而當(dāng)我們依賴注入我們真正想要的類時(shí)(如Mapper接口的代理類),就會從一級緩存中拿到FactoryBean實(shí)現(xiàn)類的實(shí)例,并判斷是否實(shí)現(xiàn)了FactoryBean接口,如果是就會調(diào)用getObject方法返回我們真正想要的實(shí)例。
那如果我們確實(shí)想要拿到的就是FactoryBean實(shí)現(xiàn)類的實(shí)例該怎么辦呢?只需要在傳入的beanName前面加上“&”符號即可。
總結(jié)
本篇分析了Mybatis如何擴(kuò)展插件以及插件的實(shí)現(xiàn)原理,但如非必要,切忌擴(kuò)展插件,如果一定要,那么一定要非常謹(jǐn)慎。另外還結(jié)合Spirng的擴(kuò)展點(diǎn)分析了Mybatis和Spring的整合原理,解決了困在我心中已久的一些疑惑,相信那也是大多數(shù)讀者的疑惑,好好領(lǐng)悟這部分內(nèi)容非常有利于我們自己對Spring進(jìn)行擴(kuò)展。
相關(guān)文章
Java中數(shù)組容器(ArrayList)設(shè)的計(jì)與實(shí)現(xiàn)
本篇文章主要跟大家介紹我們最常使用的一種容器ArrayList、Vector的原理,并且自己使用Java實(shí)現(xiàn)自己的數(shù)組容器MyArrayList,讓自己寫的容器能像ArrayList那樣工作,感興趣的可以了解一下2022-07-07java存儲以及java對象創(chuàng)建的流程(詳解)
下面小編就為大家?guī)硪黄猨ava存儲以及java對象創(chuàng)建的流程(詳解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-05-05使用maven項(xiàng)目pom.xml文件配置打包功能和靜態(tài)資源文件自帶版本號功能
在Maven項(xiàng)目中,通過pom.xml文件配置打包功能,可以控制構(gòu)建過程,生成可部署的包,同時(shí),為了緩存控制與版本更新,可以在打包時(shí)給靜態(tài)資源文件如JS、CSS添加版本號,這通常通過插件如maven-resources-plugin實(shí)現(xiàn)2024-09-09Springboot使用@WebListener?作為web監(jiān)聽器的過程解析
這篇文章主要介紹了Springboot使用@WebListener作為web監(jiān)聽器的過程,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-08-08