动态代理给原生servlet的service加上事务管理

时间:2021-11-25 02:44:02

这是一个简单的模型。

public class ProxyServiceImpl{
    //加载配置文件
    private static Map<String,String> map = new HashMap<>();
    static{
        //使用util下的ResourceBundle加载properties配置文件
        ResourceBundle resourceBundle = ResourceBundle.getBundle("peizhi");
        Enumeration<String> keys = resourceBundle.getKeys();
        while(keys.hasMoreElements()){
            String key = keys.nextElement();
            String value = resourceBundle.getString(key);
            map.put(key,value);
        }
    }

    public <T> T getService(Class<T> clazz) {
        if(!clazz.isInterface()){
            throw new RuntimeException("不是一个接口");
        }
        String className = clazz.getSimpleName();
        if(!map.containsKey(className)){
           throw new RuntimeException("未知的接口");
        }
        String string = map.get(className);
        Class<?> aClass = null;
        try {
            aClass = Class.forName(string);
        } catch (Exception e) {
            e.printStackTrace();
        }
        final Class<?> finalAClass = aClass;
        T userService1 = (T)Proxy.newProxyInstance(aClass.getClassLoader(), new Class[]{clazz}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object invoke = null;
                try {
                    System.out.println("开启事务");

                    invoke = method.invoke(finalAClass.newInstance(), args);
                    System.out.println("事务提交");
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("事务回滚");
                    throw new RuntimeException("事务出现错误");
                } finally {
                    System.out.println("关闭资源");
                }
                return invoke;
            }
        });
        return userService1;
    }
}

配置文件:

示例动态代理给原生servlet的service加上事务管理

接口名与实现类的包名+类名