Jelajahi Sumber

增强ServiceImpl泛型推断(解决多继承与代理问题).

nieqiurong 4 tahun lalu
induk
melakukan
e61e3bb90b

+ 11 - 2
mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/service/impl/ServiceImpl.java

@@ -29,6 +29,7 @@ import org.apache.ibatis.logging.LogFactory;
 import org.apache.ibatis.session.SqlSession;
 import org.mybatis.spring.SqlSessionUtils;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.ResolvableType;
 import org.springframework.transaction.annotation.Transactional;
 
 import java.io.Serializable;
@@ -80,11 +81,19 @@ public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
     }
 
     protected Class<T> currentMapperClass() {
-        return (Class<T>) ReflectionKit.getSuperClassGenericType(getClass(), 0);
+        return (Class<T>) this.getResolvableType().as(ServiceImpl.class).getGeneric(0).getType();
     }
 
     protected Class<T> currentModelClass() {
-        return (Class<T>) ReflectionKit.getSuperClassGenericType(getClass(), 1);
+        return (Class<T>) this.getResolvableType().as(ServiceImpl.class).getGeneric(1).getType();
+    }
+
+    /**
+     * @see ResolvableType
+     * @since 3.4.2
+     */
+    protected ResolvableType getResolvableType() {
+        return ResolvableType.forClass(ClassUtils.getUserClass(getClass()));
     }
 
     /**

+ 41 - 0
mybatis-plus-extension/src/test/java/com/baomidou/mybatisplus/test/service/ServiceTest.java

@@ -0,0 +1,41 @@
+package com.baomidou.mybatisplus.test.service;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/**
+ * @author nieqiurong 2021/1/19.
+ */
+public class ServiceTest {
+
+    static class Demo {
+
+    }
+
+    interface DemoMapper extends BaseMapper<Demo> {
+
+    }
+
+    static class DemoServiceImpl extends ServiceImpl<DemoMapper, Demo> {
+
+    }
+
+    static class DemoServiceExtend extends DemoServiceImpl {
+
+    }
+
+    @Test
+    @SuppressWarnings("unchecked")
+    void genericTest() {
+        IService<Demo>[] services = new IService[]{new DemoServiceImpl(), new DemoServiceExtend()};
+        for (IService<Demo> service : services) {
+            Assertions.assertEquals(Demo.class, service.getEntityClass());
+            Assertions.assertEquals(DemoMapper.class, ReflectionKit.getFieldValue(service, "mapperClass"));
+        }
+    }
+
+}