spring学习之:java jdk动态代理二次封装

环境

<dependencies>

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.12</version>

<scope>test</scope>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

<version>5.3.23</version>

</dependency>

</dependencies>

核心代理类封装
public class NewProxy<T> {
    private T thisProxy;
    public NewProxy(T thisProxy) {//使用代理对象必须有被代理对象的存在
        this.thisProxy = thisProxy;
    }
    public T getProxy(utilFun utilFunObj){
            return (T)Proxy.newProxyInstance(
                    thisProxy.getClass().getClassLoader(),//获取被代理对象的类启动器
                    thisProxy.getClass().getInterfaces(),//获取被代理对象的接口
                    (proxy, method, args) -> {
                        utilFunObj.before();
                        Object o=method.invoke(thisProxy,args);
                        utilFunObj.after();
                        return o;
                    }//实现InvocationHandler接口的匿名对象
                    );





    }


}
外置接口
public interface utilFun {
    Object before();
    Object after();
}
被代理类的实现接口
public interface EmployeeService {
    int add();
    int del();
    int set();
    void update();

}
被代理类
public class EmployeeServiceImpl implements EmployeeService {

    @Override
    public int add() {
        System.out.println("新增功能");
        return 0;
    }

    @Override
    public int del() {
        System.out.println(" 删除功能");

        return 0;
    }

    @Override
    public int set() {
        System.out.println(" 修改功能 ");

        return 0;
    }

    @Override
    public void update() {
        System.out.println("更新功能");


    }
}
测试
    @Test
    public void proxyFunction(){
        
        EmployeeService EmployeeService = new NewProxy<EmployeeService>(new EmployeeServiceImpl()).getProxy(new utilFun() {
            @Override
            public Object before() {
                System.out.println("log b");
                return null;
            }

            @Override
            public Object after() {
                System.out.println("log a");
                return null;
            }
        });
        EmployeeService.add();
        EmployeeService.del();
        EmployeeService.set();
        EmployeeService.update();
        

    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值