1.建立实体User
package com.example.xiangxue.demo.proxy.jdkproxy; public class User { public String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
2.要增强的接口及其实现类
package com.example.xiangxue.demo.proxy.jdkproxy; public interface Userservice { public void addUser(User user); }
package com.example.xiangxue.demo.proxy.jdkproxy; public class UserServiceImpl implements Userservice { @Override public void addUser(User user) { System.out.println("用户添加成功····"); } }
3.写一个类实现InvocationHandler接口,并持有要增强的类,在重写的invoke方法中编写增强的代码。
package com.example.xiangxue.demo.proxy.jdkproxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class UserProxy implements InvocationHandler { public Object realObj; public Object getRealObj() { return realObj; } public void setRealObj(Object realObj) { this.realObj = realObj; } public UserProxy(Object realObj) { super(); this.realObj = realObj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (args[0] instanceof User){ User u = (User)args[0]; if (u.getName().trim().length() < 2) { throw new RuntimeException("用户名字不合规 小于2了。。"); } } Object ret = method.invoke(realObj,args); System.out.println("数据库操作成功····"); return ret; } }
4.接下来分为几个步骤:
第一.,new出要增强的业务方法实例,给到我们编写的代理类;
第二,把要增强的业务接口的classLoader,业务接口,以及编写的代理类作为参数传给Proxy.newProxyInstance方法,可以得到增强后的业务类
第三,使用增强后的业务类即可,此时方法已经增强;
package com.example.xiangxue.demo.proxy.jdkproxy; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.lang.reflect.Proxy; @SpringBootApplication public class Test { public static void main(String[] args) { User user = new User(); user.setName("1"); Userservice userservice = new UserServiceImpl(); UserProxy userProxy = new UserProxy(userservice); Userservice proxy = (Userservice)Proxy.newProxyInstance(userservice.getClass().getClassLoader(),userservice.getClass().getInterfaces(),userProxy); proxy.addUser(user); } }
运行结果:增强生效