本篇参考java反射调用mapper中的接口_反射获取mapper并调方法-CSDN博客
本文更多的是解决在使用参考博客文档的过程中遇到的问题,在用这位博主方法时,发现反射是不能获取写在XML中的方法,至于为什么就不懂了,希望有大佬解答一下。
在接口中使用反射无法创建实例,因此需要动态代理
/** 动态代理 **/
@Component
public class MyInvocationHandler implements InvocationHandler {
@Autowired
private SqlSession sqlSession;
private static Object target;
private static SqlSession session;
@PostConstruct
public void init() {
session = sqlSession;
}
public void setTarget(Class clazz) {
target = session.getMapper(clazz);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(target, args);
}
}
有了动态代理,就能在接口使用反射:
/**通过反射调用mapper查数据**/
String mapperStr = "mapper路径";
Class clazz = Class.forName(mapperStr);
if (null==clazz) throw new NullPointerException();
/**创建动态代理并使用反射**/
MyInvocationHandler myInvocationHandler = new MyInvocationHandler();
myInvocationHandler.setTarget(clazz);
Object object = Proxy.newProxyInstance(clazz.getClassLoader(),
new Class[]{clazz},
myInvocationHandler);
Method selectById = object.getClass().getDeclaredMethod("selectAll");
/**调用方法查询数据库**/
selectById.setAccessible(true);
Object o = selectById.invoke(object);
System.out.println(o);
注意事项:(1)反射获取mapper中方法时,只能获取下述代码块中第五个用注解写的方法,无法获取写在xml文件的方法。本人在使用其他up主写的代码时,出现了此问题,最后发现是不能获取写在XML文件方法
(2)参考博主的那篇文档中,博主用到了SqlSession,因为在BaseController接口中无法注入Bean对象,所以在动态代理实体类中,用Autowired注入了SqlSession
mapper中的方法:
CaseDo selectById(@Param("caseBasicId") String caseBasicId);
int updateLine(CaseDo vo);
CaseDo selectByIdAndType(String id,String type);
int insert(CaseSubLaspDo caseSubLaspDo);
@Select("select * from STUDENT")
List<Student> selectAll();