This article is original, please indicate the source

As we know, The Mapper of Mybatis generally has only one interface and the corresponding XML file. In fact, Mybatis is also the entity object of the corresponding interface generated by the dynamic proxy. Here we can copy the principle to achieve a simple, complex readers can realize it by themselves.

The overall implementation is relatively simple. First we need to prepare a few things:

  • A Mapper interface:MyMapperFor simplicity, only two simple methods are defined and returnedString
  • A TXT file that mimics Mapper XML:MyMapper.txt, where a semicolon separates two fields: method name and return value
  • A proxy class:MapperProxyFor dynamic generationMyMapperThe object of
  • A testMainClasses andmainmethods

MyMapper interface definition:

public interface MyMapper {

    String getName(a);

    String getAge(a);
}
Copy the code

MyMapper. TXT content:

getName:wanli
getAge:29
Copy the code

MapperProxy class definition:

public class MapperProxy implements InvocationHandler {

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        // The function returns the value obtained from the TXT file
        BufferedReader reader = new BufferedReader(new FileReader("MyMapper.txt"));
        String line = null;
        Object result = null;

        while((line = reader.readLine()) ! =null) {
            String[] lineStrs = line.split(":");
            if (lineStrs[0].trim().equals(method.getName())) {
                result = lineStrs[1].trim();
                break;
            }
        }

        reader.close();
        returnresult; }}Copy the code

Test classes and methods:

public class Main {

    public static void main(String[] args) {

        // The actual dynamic proxy generates dynamic objects
        MyMapper mapper = (MyMapper) Proxy.newProxyInstance(MyMapper.class.getClassLoader(), new Class[]{MyMapper.class}, newMapperProxy()); System.out.println(mapper.getName()); System.out.println(mapper.getAge()); }}Copy the code

Output result:

wanli
29
Copy the code

See, here is a dynamic proxy that does not define a specific interface implementation class, but implements the corresponding effect.