Mybatis源码阅读(一):Mybatis初始化1.2 —— 解析别名、插件、对象工厂、反射工具箱、环境
*************************************優(yōu)雅的分割線 **********************************
分享一波:程序員賺外快-必看的巔峰干貨
如果以上內(nèi)容對你覺得有用,并想獲取更多的賺錢方式和免費的技術(shù)教程
請關(guān)注微信公眾號:HB荷包
一個能讓你學(xué)習(xí)技術(shù)和賺錢方法的公眾號,持續(xù)更新
*************************************優(yōu)雅的分割線 **********************************
SimpleExecutor
接上一節(jié) 上一節(jié):解析properties和settings
解析typeAliases
typeAliases節(jié)點用于配置別名。別名在mapper中使用resultType時會使用到,是對實體類的簡寫。
別名有兩種配置方式
1.通過package,直接掃描指定包下所有的類,注冊別名
2.通過typeAliase,指定某個類為其注冊別名
別名注冊代碼如下
注冊別名
掃包后獲取到包下所有的類之后,會為這些類生成別名,并將其注冊到Configuration中
/*** 指定包名,將這個包下所有的類都注冊別名** @param packageName*/public void registerAliases(String packageName) {registerAliases(packageName, Object.class);}/*** 為指定包下所有的類注冊別名** @param packageName* @param superType*/public void registerAliases(String packageName, Class<?> superType) {ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<>();// 掃描指定包下所有繼承了superType的類resolverUtil.find(new ResolverUtil.IsA(superType), packageName);// 獲取匹配到的所有的類Set<Class<? extends Class<?>>> typeSet = resolverUtil.getClasses();for (Class<?> type : typeSet) {// 過濾掉內(nèi)部類、接口、抽象類if (!type.isAnonymousClass() && !type.isInterface() && !type.isMemberClass()) {registerAlias(type);}}}/*** 注冊指定類的別名* @param type*/public void registerAlias(Class<?> type) {// 得到類的簡寫名稱,即不帶包名的名稱// 因此在mybatis掃描包下,不允許有同樣類名的類存在// 否則在啟動時就會報錯String alias = type.getSimpleName();Alias aliasAnnotation = type.getAnnotation(Alias.class);if (aliasAnnotation != null) {// 如果有Alias注解,就以Alias注解指定的別名為準(zhǔn)// 該注解可以用于解決被掃描包下含有相同名稱類的問題alias = aliasAnnotation.value();}registerAlias(alias, type);}/*** 注冊別名* @param alias 別名* @param value 指定的類*/public void registerAlias(String alias, Class<?> value) {if (alias == null) {throw new TypeException("The parameter alias cannot be null");}// 別名轉(zhuǎn)為小寫String key = alias.toLowerCase(Locale.ENGLISH);// 如果已經(jīng)有了這個別名,并且這個別名中取到的值不為null,并且取到的值和傳進來的類不相同就報錯if (typeAliases.containsKey(key) && typeAliases.get(key) != null && !typeAliases.get(key).equals(value)) {throw new TypeException("The alias '" + alias + "' is already mapped to the value '" + typeAliases.get(key).getName() + "'.");}// 將別名放到typeAliases中。key是別名,因此別名不可以重復(fù)typeAliases.put(key, value);}在注冊別名時,會使用到ResolverUtil工具類。該工具類可以根據(jù)指定的條件去查找指定包下的類。該類有個內(nèi)部接口Test,接口中只有一個matches方法,用于根據(jù)指定的規(guī)則去匹配。Test接口有兩個實現(xiàn)。ISA用于檢測該類是否繼承了指定的類或者接口,而AnnotatedWith則用于檢測是否添加了指定的注釋,代碼比較簡單這里就不貼了。這里使用到了find方法,用于匹配指定包下所有繼承了superType的類
public ResolverUtil<T> find(Test test, String packageName) {String path = getPackagePath(packageName);try {// 獲取指定包下所有的文件名List<String> children = VFS.getInstance().list(path);for (String child : children) {if (child.endsWith(".class")) {addIfMatching(test, child);}}} catch (IOException ioe) {log.error("Could not read package: " + packageName, ioe);}return this;}/*** 如果匹配成功,就添加到matches中** @param test the test used to determine if the class matches* @param fqn the fully qualified name of a class*/@SuppressWarnings("unchecked")protected void addIfMatching(Test test, String fqn) {try {String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');ClassLoader loader = getClassLoader();if (log.isDebugEnabled()) {log.debug("Checking to see if class " + externalName + " matches criteria [" + test + "]");}Class<?> type = loader.loadClass(externalName);if (test.matches(type)) {matches.add((Class<T>) type);}} catch (Throwable t) {log.warn("Could not examine class '" + fqn + "'" + " due to a " +t.getClass().getName() + " with message: " + t.getMessage());}}解析plugins
mybatis擁有強大的插件機制,可以通過配置mybatis攔截器來統(tǒng)一對sql、參數(shù)、返回集等進行處理,該功能廣泛運用與分頁、創(chuàng)建人等字段賦值、邏輯刪除、樂觀鎖等插件的編寫中。mybatis的攔截器編寫難度比spring mvc高得多,想要熟練地編寫mybatis攔截器,需要對源碼比較熟悉。
解析攔截器的代碼比較簡單,plugin節(jié)點需要配置一個interceptor屬性,該屬性是自定義攔截器的全類名。在該方法中會先獲取到該屬性,通過該屬性對應(yīng)攔截器的默認構(gòu)造去創(chuàng)建實例,并添加到Configuration中。
/*** 解析plugins節(jié)點* plugin節(jié)點用于配置插件* 即 mybatis攔截器** @param parent* @throws Exception*/private void pluginElement(XNode parent) throws Exception {if (parent != null) {// 獲取子節(jié)點,子節(jié)點就是所配置的攔截器for (XNode child : parent.getChildren()) {// 獲得攔截器全類名String interceptor = child.getStringAttribute("interceptor");// 將節(jié)點下的節(jié)點封裝成propertiesProperties properties = child.getChildrenAsProperties();// 根據(jù)攔截器的全類名,通過默認構(gòu)造方法創(chuàng)建一個實例Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).getDeclaredConstructor().newInstance();// 將攔截器節(jié)點下的properties放到攔截器中interceptorInstance.setProperties(properties);// 將攔截器添加到配置中configuration.addInterceptor(interceptorInstance);}}}解析ObjectFactory節(jié)點
objectFactory用來處理查詢得到的結(jié)果集,創(chuàng)建對象去將結(jié)果集封裝到對象中。
mybatis默認的對象工廠是用無參構(gòu)造或者有參構(gòu)造去創(chuàng)建對象,而如果開發(fā)者想在創(chuàng)建對象前對其進行一些初始化操作或者處理一些業(yè)務(wù)方面的邏輯,就可以自定義對象工廠并進行配置。對象工廠的解析比較簡單,拿到type屬性去創(chuàng)建一個實例并添加到Configuration即可。
/*** 解析objectFactory節(jié)點* objectFactory用來處理查詢得到的結(jié)果集* 創(chuàng)建對象去將結(jié)果集封裝到對象中* mybatis默認的object工廠是用無參構(gòu)造或者有參構(gòu)造去創(chuàng)建對象* 而如果開發(fā)者想在創(chuàng)建對象前對其中的一些屬性做初始化操作* 或者做一些業(yè)務(wù)方面的邏輯* 就可以自己去創(chuàng)建對象工廠并進行配置** @param context* @throws Exception*/private void objectFactoryElement(XNode context) throws Exception {if (context != null) {// 拿到objectFactory節(jié)點的type屬性,該屬性為對象工廠的全類名String type = context.getStringAttribute("type");// 拿到節(jié)點下所有的propertiesProperties properties = context.getChildrenAsProperties();// 根據(jù)type對應(yīng)的類,通過默認構(gòu)造去創(chuàng)建一個實例ObjectFactory factory = (ObjectFactory) resolveClass(type).getDeclaredConstructor().newInstance();// 將properties放入對象工廠factory.setProperties(properties);// 將對象工廠添加到配置中去configuration.setObjectFactory(factory);}}解析objectWrapperFactory和reflectorFactory
這兩個節(jié)點的解析很簡單,這里只貼上代碼給讀者去閱讀,很容易就能理解。
/*** 解析objectWrapperFactory節(jié)點** @param context* @throws Exception*/private void objectWrapperFactoryElement(XNode context) throws Exception {if (context != null) {// 獲取到type屬性String type = context.getStringAttribute("type");// 根據(jù)type屬性對應(yīng)的類去創(chuàng)建對象ObjectWrapperFactory factory = (ObjectWrapperFactory) resolveClass(type).getDeclaredConstructor().newInstance();// 將對象放到配置中configuration.setObjectWrapperFactory(factory);}}/*** 解析reflectorFactory節(jié)點。代碼比較簡單就不寫了。* 解析流程和objectWrapperFactory一毛一樣** @param context* @throws Exception*/private void reflectorFactoryElement(XNode context) throws Exception {if (context != null) {String type = context.getStringAttribute("type");ReflectorFactory factory = (ReflectorFactory) resolveClass(type).getDeclaredConstructor().newInstance();configuration.setReflectorFactory(factory);}}處理settings節(jié)點
在前一篇文章,已經(jīng)將解析settings節(jié)點的代碼講解完畢,該方法則是用來將解析后的settings節(jié)點中的配置,一一添加到Configuration。代碼簡單粗暴,就是一堆set
/*** 將settings節(jié)點的配置set到Configuration中** @param props*/private void settingsElement(Properties props) {configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));configuration.setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.valueOf(props.getProperty("autoMappingUnknownColumnBehavior", "NONE")));configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true));configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty("proxyFactory")));configuration.setLazyLoadingEnabled(booleanValueOf(props.getProperty("lazyLoadingEnabled"), false));configuration.setAggressiveLazyLoading(booleanValueOf(props.getProperty("aggressiveLazyLoading"), false));configuration.setMultipleResultSetsEnabled(booleanValueOf(props.getProperty("multipleResultSetsEnabled"), true));configuration.setUseColumnLabel(booleanValueOf(props.getProperty("useColumnLabel"), true));configuration.setUseGeneratedKeys(booleanValueOf(props.getProperty("useGeneratedKeys"), false));configuration.setDefaultExecutorType(ExecutorType.valueOf(props.getProperty("defaultExecutorType", "SIMPLE")));configuration.setDefaultStatementTimeout(integerValueOf(props.getProperty("defaultStatementTimeout"), null));configuration.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), null));configuration.setDefaultResultSetType(resolveResultSetType(props.getProperty("defaultResultSetType")));configuration.setMapUnderscoreToCamelCase(booleanValueOf(props.getProperty("mapUnderscoreToCamelCase"), false));configuration.setSafeRowBoundsEnabled(booleanValueOf(props.getProperty("safeRowBoundsEnabled"), false));configuration.setLocalCacheScope(LocalCacheScope.valueOf(props.getProperty("localCacheScope", "SESSION")));configuration.setJdbcTypeForNull(JdbcType.valueOf(props.getProperty("jdbcTypeForNull", "OTHER")));configuration.setLazyLoadTriggerMethods(stringSetValueOf(props.getProperty("lazyLoadTriggerMethods"), "equals,clone,hashCode,toString"));configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty("safeResultHandlerEnabled"), true));configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty("defaultScriptingLanguage")));configuration.setDefaultEnumTypeHandler(resolveClass(props.getProperty("defaultEnumTypeHandler")));configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty("callSettersOnNulls"), false));configuration.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), true));configuration.setReturnInstanceForEmptyRow(booleanValueOf(props.getProperty("returnInstanceForEmptyRow"), false));configuration.setLogPrefix(props.getProperty("logPrefix"));configuration.setConfigurationFactory(resolveClass(props.getProperty("configurationFactory")));}解析environments
該節(jié)點標(biāo)識環(huán)境配置。所謂環(huán)境,就是只運行時需要的一系列參數(shù),也可以理解成開發(fā)中常說的“開發(fā)環(huán)境”“測試環(huán)境”“生產(chǎn)環(huán)境”。環(huán)境最直觀的就是在不同環(huán)境下連接不同的數(shù)據(jù)庫。
environments節(jié)點下提供了數(shù)據(jù)源和事務(wù)配置。
/*** 解析environments節(jié)點* 該節(jié)點表示環(huán)境配置* 所謂環(huán)境,就是指運行時環(huán)境,即開發(fā)環(huán)境、測試環(huán)境、生產(chǎn)環(huán)境* 環(huán)境最直觀的提現(xiàn)就是在不同環(huán)境下數(shù)據(jù)庫不同* environments節(jié)點下就提供了數(shù)據(jù)源和事務(wù)配置** @param context* @throws Exception*/private void environmentsElement(XNode context) throws Exception {if (context != null) {if (environment == null) {// 獲取默認的環(huán)境idenvironment = context.getStringAttribute("default");}for (XNode child : context.getChildren()) {// 拿到子節(jié)點的id。父節(jié)點的default屬性對應(yīng)的就是子節(jié)點idString id = child.getStringAttribute("id");if (isSpecifiedEnvironment(id)) {// 解析事務(wù)管理器TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));// 解析數(shù)據(jù)工廠DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));// 從工廠中拿到數(shù)據(jù)庫DataSource dataSource = dsFactory.getDataSource();// 創(chuàng)建環(huán)境并set到Configuration中去Environment.Builder environmentBuilder = new Environment.Builder(id).transactionFactory(txFactory).dataSource(dataSource);configuration.setEnvironment(environmentBuilder.build());}}}}解析的邏輯中,需要一并解析事務(wù)工廠和DataSource工廠。代碼比較簡單,和objectWrapperFactory一樣,這里就不貼了
解析databaseIdProvider
該節(jié)點用于提供多數(shù)據(jù)源支持。這里的多數(shù)據(jù)源并非指多個數(shù)據(jù)庫,而是指多個數(shù)據(jù)庫產(chǎn)品。這里的代碼和objectWrapperFactory比較類似,不做過多解釋。
/*** 解析databaseIdProvider節(jié)點* 該節(jié)點用于提供多數(shù)據(jù)源支持* 這里的多數(shù)據(jù)源并非指多個數(shù)據(jù)庫* 而是指多個數(shù)據(jù)庫產(chǎn)品* 這里的代碼和objectFactory類似** @param context* @throws Exception*/private void databaseIdProviderElement(XNode context) throws Exception {DatabaseIdProvider databaseIdProvider = null;if (context != null) {String type = context.getStringAttribute("type");// awful patch to keep backward compatibilityif ("VENDOR".equals(type)) {type = "DB_VENDOR";}Properties properties = context.getChildrenAsProperties();databaseIdProvider = (DatabaseIdProvider) resolveClass(type).getDeclaredConstructor().newInstance();databaseIdProvider.setProperties(properties);}// 獲取當(dāng)前環(huán)境Environment environment = configuration.getEnvironment();if (environment != null && databaseIdProvider != null) {String databaseId = databaseIdProvider.getDatabaseId(environment.getDataSource());configuration.setDatabaseId(databaseId);}}結(jié)語
昨天加班填坑加到了12點,就沒有繼續(xù)為代碼加注釋,今天在空閑的時候就繼續(xù)填坑了。目前對mybatis-config.xml文件的解析基本接近尾聲,還差typeHandlers和mappers兩個節(jié)點沒有進行注釋。相信看了這兩篇文章的讀者對于解析配置文件的邏輯已經(jīng)有了一定的理解,因此自己閱讀后面兩個節(jié)點的代碼解析應(yīng)該不難。明天或者后天會將最后的兩個節(jié)點的解析補上
*************************************優(yōu)雅的分割線 **********************************
分享一波:程序員賺外快-必看的巔峰干貨
如果以上內(nèi)容對你覺得有用,并想獲取更多的賺錢方式和免費的技術(shù)教程
請關(guān)注微信公眾號:HB荷包
一個能讓你學(xué)習(xí)技術(shù)和賺錢方法的公眾號,持續(xù)更新
*************************************優(yōu)雅的分割線 **********************************
SimpleExecutor
總結(jié)
以上是生活随笔為你收集整理的Mybatis源码阅读(一):Mybatis初始化1.2 —— 解析别名、插件、对象工厂、反射工具箱、环境的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java对日期Date类进行加减运算、年
- 下一篇: fatal: Could not rea