1919import io .mybatis .mapper .BaseMapper ;
2020import io .mybatis .provider .EntityClassFinder ;
2121import org .mybatis .spring .SqlSessionTemplate ;
22+ import org .springframework .beans .BeansException ;
2223import org .springframework .context .ApplicationContext ;
24+ import org .springframework .context .ApplicationContextAware ;
2325import org .springframework .context .ApplicationListener ;
2426import org .springframework .context .event .ContextRefreshedEvent ;
2527
3537 * @param <M> 实体对应的 Mapper
3638 * @author liuzh
3739 */
38- public class MapperProvider <T , I extends Serializable , M extends BaseMapper <T , I >> implements ApplicationListener <ContextRefreshedEvent > {
40+ public class MapperProvider <T , I extends Serializable , M extends BaseMapper <T , I >> implements ApplicationContextAware , ApplicationListener <ContextRefreshedEvent > {
3941 /**
4042 * Spring 上下文
4143 */
@@ -76,9 +78,17 @@ public static <T, I extends Serializable, M extends BaseMapper<T, I>> MapperProv
7678 return (MapperProvider <T , I , M >) applicationContext .getBean (instanceName );
7779 }
7880
81+ @ Override
82+ public void setApplicationContext (ApplicationContext applicationContext ) throws BeansException {
83+ MapperProvider .applicationContext = applicationContext ;
84+ }
85+
7986 @ Override
8087 public void onApplicationEvent (ContextRefreshedEvent event ) {
81- MapperProvider .applicationContext = event .getApplicationContext ();
88+ this .initMapper ();
89+ }
90+
91+ protected void initMapper () {
8292 this .sqlSessionTemplate .getConfiguration ().getMapperRegistry ().getMappers ().forEach (mapper -> {
8393 addMapper (mapper , this .sqlSessionTemplate .getMapper (mapper ));
8494 });
@@ -91,9 +101,9 @@ public void onApplicationEvent(ContextRefreshedEvent event) {
91101 * @param mapper Mapper 实例
92102 */
93103 public void addMapper (Class <?> type , Object mapper ) {
94- if (type != null && BaseMapper .class .isAssignableFrom (type )) {
104+ if (type != null && mapper != null && BaseMapper .class .isAssignableFrom (type )) {
95105 EntityClassFinder .find (type , null ).ifPresent (clazz -> {
96- if (mapper != null ) {
106+ if (! modelMapper . containsKey ( clazz ) ) {
97107 modelMapper .put (clazz , (BaseMapper <T , I >) mapper );
98108 }
99109 });
@@ -107,6 +117,13 @@ public void addMapper(Class<?> type, Object mapper) {
107117 * @return Mapper 接口
108118 */
109119 public M baseMapper (Class <T > modelClass ) {
120+ if (!modelMapper .containsKey (modelClass )) {
121+ synchronized (this ) {
122+ if (!modelMapper .containsKey (modelClass )) {
123+ this .initMapper ();
124+ }
125+ }
126+ }
110127 if (modelMapper .containsKey (modelClass )) {
111128 return (M ) modelMapper .get (modelClass );
112129 }
0 commit comments