Mybatis集成到Spring容器的詳細(xì)步驟
在現(xiàn)在的JavaEE開發(fā)過程中,我們經(jīng)常會使用到Spring+SpringMVC+Mybatis這個組合。那么Mybatis是如何集成到Spring中的呢?
本文只講@MapperScan注解方式的整個過程。其他方式類似。
Mapper集成到Spring使用大概分為如下幾個步驟:
- 使用Import方式引入注冊類MapperScannerRegistrar
- MapperScannerRegistrar獲取配置參數(shù)。
- 使用ClassPathMapperScanner進(jìn)行掃描。比如掃描basePackages下面的類。然后對掃描的bean定義處理,比如替換beanClass為MapperFactoryBean.class
- Sping進(jìn)行注冊bean,調(diào)用到MapperFactoryBean的getObject()。返回一個代理對象MapperProxy
- 使用代理對象進(jìn)行增刪改查,接口方法會被代理到MapperMethod,最終用sqlSession進(jìn)行增刪改查。
一、使用Import方式引入注冊類MapperScannerRegistrar
先看@MapperScan代碼
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Import(MapperScannerRegistrar.class) public @interface MapperScan{
這個注解中有一個@Import(MapperScannerRegistrar.class)。
這個@Import在Spring解析中會先去實例化一個MapperScannerRegistrar.class的單例bean到Spring中。
二、MapperScannerRegistrar
MapperScannerRegistrar實現(xiàn)了ImportBeanDefinitionRegistrar接口。ImportBeanDefinitionRegistrar會返回@Import中定義參數(shù),然后我們使用
ClassPathMapperScanner掃描。
@Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(MapperScan.class.getName())); ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry); // this check is needed in Spring 3.1 if (resourceLoader != null) { scanner.setResourceLoader(resourceLoader); } Class<? extends Annotation> annotationClass = annoAttrs.getClass("annotationClass"); if (!Annotation.class.equals(annotationClass)) { scanner.setAnnotationClass(annotationClass); } Class<?> markerInterface = annoAttrs.getClass("markerInterface"); if (!Class.class.equals(markerInterface)) { scanner.setMarkerInterface(markerInterface); } Class<? extends BeanNameGenerator> generatorClass = annoAttrs.getClass("nameGenerator"); if (!BeanNameGenerator.class.equals(generatorClass)) { scanner.setBeanNameGenerator(BeanUtils.instantiateClass(generatorClass)); } Class<? extends MapperFactoryBean> mapperFactoryBeanClass = annoAttrs.getClass("factoryBean"); if (!MapperFactoryBean.class.equals(mapperFactoryBeanClass)) { scanner.setMapperFactoryBean(BeanUtils.instantiateClass(mapperFactoryBeanClass)); } scanner.setSqlSessionTemplateBeanName(annoAttrs.getString("sqlSessionTemplateRef")); scanner.setSqlSessionFactoryBeanName(annoAttrs.getString("sqlSessionFactoryRef")); List<String> basePackages = new ArrayList<String>(); for (String pkg : annoAttrs.getStringArray("value")) { if (StringUtils.hasText(pkg)) { basePackages.add(pkg); } } for (String pkg : annoAttrs.getStringArray("basePackages")) { if (StringUtils.hasText(pkg)) { basePackages.add(pkg); } } for (Class<?> clazz : annoAttrs.getClassArray("basePackageClasses")) { basePackages.add(ClassUtils.getPackageName(clazz)); } scanner.registerFilters(); scanner.doScan(StringUtils.toStringArray(basePackages)); }
三、 使用ClassPathMapperScanner進(jìn)行掃描
ClassPathMapperScanner繼承了ClassPathBeanDefinitionScanner,可以掃描我們需要的bean定義。比如我們經(jīng)常配置的basePackages。他就會給我掃描下面所有的類,然后對掃描的Mapper bean定義進(jìn)行處理。后面Spring對掃描的beanDefintion進(jìn)行初始化等操作。
下面是ClassPathMapperScanner中處理bean定義的方法
private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) { GenericBeanDefinition definition; //遍歷bean定義 for (BeanDefinitionHolder holder : beanDefinitions) { //BeanDefinitionHolder會包裝一個BeanDefinition 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 //此處把bean定義的構(gòu)造方法中加一個參數(shù) //其實后面調(diào)用的MapperFactoryBean的這個構(gòu)造方法,這個構(gòu)造方法需要一個class。這個class就是掃描出來的Mapper的class //public MapperFactoryBean(Class<T> mapperInterface) { // this.mapperInterface = mapperInterface; // } definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); // issue #59 // 此處會把 beanClass替換為MapperFactoryBean.class,后續(xù)spring進(jìn)行初始化的時候就會通過MapperFactoryBean.class進(jìn)行反射 definition.setBeanClass(this.mapperFactoryBean.getClass()); //添加參數(shù) definition.getPropertyValues().add("addToConfig", this.addToConfig); //下面的if沒有設(shè)置一般都不會進(jìn)入 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() + "'."); } //設(shè)置@autowire的方式為class definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); } } }
四、 Sping進(jìn)行注冊MapperFactoryBean
在Spring中有一個比較特殊的bean較FactoryBean。這個bean為使用者提供了一種靈活初始化bean的方式,Spring在構(gòu)造FactoryBean類型的bean的時候會調(diào)用FactoryBean.getObject()進(jìn)行初始化bean。
下面是MapperFactoryBean初始化bean的方法
@Override public T getObject() throws Exception { //會返回一個MapperProxy的類,Spring就會把MapperProxy注冊到容器中,當(dāng)使用Mapper的類型獲取bean的時候其實spring返回的是一個MapperProxy代理對象。 return getSqlSession().getMapper(this.mapperInterface); }
返回MapperProxy的方法是通過MapperRegistry.getMapper返回的
public <T> T getMapper(Class<T> type, SqlSession sqlSession) { final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type); if (mapperProxyFactory == null) { throw new BindingException("Type " + type + " is not known to the MapperRegistry."); } try { return mapperProxyFactory.newInstance(sqlSession); } catch (Exception e) { throw new BindingException("Error getting mapper instance. Cause: " + e, e); } }
進(jìn)入MapperProxyFactory類
public class MapperProxyFactory<T> { //mapper接口的class private final Class<T> mapperInterface; //MapperMethod緩存 private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>(); public MapperProxyFactory(Class<T> mapperInterface) { this.mapperInterface = mapperInterface; } public Class<T> getMapperInterface() { return mapperInterface; } public Map<Method, MapperMethod> getMethodCache() { return methodCache; } @SuppressWarnings("unchecked") protected T newInstance(MapperProxy<T> mapperProxy) { //使用JDK動態(tài)代理為mapperInterface創(chuàng)建一個mapperProxy的動態(tài)代理,后續(xù)調(diào)用mapperInterface方法的時候會進(jìn)入mapperProxy的invoke方法。invoke會代理mapperInterface的方法調(diào)用。 return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy); } public T newInstance(SqlSession sqlSession) { //new一個MapperProxy代理對象 final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache); return newInstance(mapperProxy); } }
五. 使用代理對象進(jìn)行增刪改查
MapperProxy其實就是一個InvocationHandler,MapperProxy代理所有的Mapper方法調(diào)用。
public class MapperProxy<T> implements InvocationHandler, Serializable { private static final long serialVersionUID = -6424540398559729838L; private final SqlSession sqlSession; private final Class<T> mapperInterface; private final Map<Method, MapperMethod> methodCache; public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) { this.sqlSession = sqlSession; this.mapperInterface = mapperInterface; this.methodCache = methodCache; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { //代理的對象是否為實體類 if (Object.class.equals(method.getDeclaringClass())) { return method.invoke(this, args); } else if (isDefaultMethod(method)) {//是否為接口的default方法 return invokeDefaultMethod(proxy, method, args); } } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); } //接口Mapper一般都是進(jìn)入這里,這邊會用一個MapperMethod進(jìn)行調(diào)用,里面其實就是一個sqlSeesion的調(diào)用。 final MapperMethod mapperMethod = cachedMapperMethod(method); return mapperMethod.execute(sqlSession, args); }
到這里mybatis中Mapper如何集成到Spring的大概就完了。
那么sqlSession如何集成到Spring的呢?
其實很簡單,sqlSession其實需要我們自己手動配置,mybatis-spring中為我們提供了一個SqlSessionFactoryBean,這個也是一個FactoryBean。SqlSessionFactoryBean會返回一個SqlSessionFactory。SqlSessionFactory注冊到Spring中。在使用sqlSession的地方直接通過SqlSessionFactory返回即可。
到此這篇關(guān)于Mybatis是如何集成到Spring容器中的的文章就介紹到這了,更多相關(guān)Mybatis集成到Spring容器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
VSCode搭建Java開發(fā)環(huán)境的超詳細(xì)步驟
VSCode是一款多平臺的源代碼編輯器,支持多種編程語言,它輕量級、功能強大,通過豐富的插件生態(tài)系統(tǒng)可以支持更多語言和運行時,如C++、C#、Java、Python等,這篇文章主要介紹了VSCode搭建Java開發(fā)環(huán)境的超詳細(xì)步驟,需要的朋友可以參考下2024-10-10Spring Cloud Gateway Hystrix fallback獲取異常信息的處理
這篇文章主要介紹了Spring Cloud Gateway Hystrix fallback獲取異常信息的處理方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07使用遞歸算法結(jié)合數(shù)據(jù)庫解析成Java樹形結(jié)構(gòu)的代碼解析
這篇文章主要介紹了使用遞歸算法結(jié)合數(shù)據(jù)庫解析成Java樹形結(jié)構(gòu)的代碼解析的相關(guān)資料,需要的朋友可以參考下2017-09-09