如何使用动态代理获取配置文件中的sql
- 首先定义Select注解,可以用来标记sql
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Select {
String[] value();
}
- 使用注解方式写sql
public interface StudentMapper {
@Select("select * from student")
void selectAll();
}
- 通过代理传入的方法获取方法对应的注解内容即sql
public class MyInvocationHandler implements InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Select select = method.getAnnotation(Select.class);
String sql = select.value()[0];
System.out.println("get sql is:"+ sql);
return null;
}
}
- 通过jdk的动态代理,获取代理类对象
public class MySession {
public static Object getMapper(Class clazz) {
Class[] clazzs = new Class[]{clazz};
MyInvocationHandler myInvocationHandler = new MyInvocationHandler();
Object object = Proxy.newProxyInstance(MySession.class.getClassLoader(), clazzs, myInvocationHandler);
return object;
}
}
- 通过代理对象执行被代理对象的方法
public class MyBatisTest {
public static void main(String[] args) {
StudentMapper studentMapper = (StudentMapper) MySession.getMapper(StudentMapper.class);
studentMapper.selectAll();
}
}
输出结果:
get sql is:select * from student
Process finished with exit code 0