一、JDK动态代理
缺点:目标对象必须实现一个或多个接口,如果没有,可以使cglib技术
Proxy.newProxyInstance(
classLoader, //目标类的类加载器
interfaces, //目标类的接口列表
invocationHandler //交叉业务逻辑
)
代码实现:
UserService userService = (UserService) Proxy.newProxyInstance( UserServiceImpl.class.getClassLoader(),//目标类的类加载器 new Class[]{UserService.class},//目标类的接口列表 new InvocationHandler() {//交叉业务逻辑 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //1.打印日志 System.out.println(method.getName()+" 开始 :["+new Date().getTime()+"]"); //2.执行业务 Object returnValue = null; try { returnValue=method.invoke(new UserServiceImpl(),args); System.out.println("提交事务"); }catch (Exception e){ System.out.println("回滚...."); throw e; } return returnValue; } } );
接口
public interface UserService { public void login(String username, String password); public String logout(); }
public class UserServiceImpl implements UserService { @Override public void login(String username, String password) { System.out.println("登录:"+username+","+password); } @Override public String logout() { System.out.println("666"); return "byebye"; } }
二、cglib技术
1.添加jar包,版本随自己喜欢
<dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>${cglib.version}</version> </dependency>
2.用法
Enhancer.create(
class,//目标类的类型
new invocationhandler //交叉业务逻辑
)
具体实现
public static void main(final String[] args) { Hello hello = (Hello) Enhancer.create( Hello.class, new InvocationHandler() { @Override public Object invoke(Object o, Method method, Object[] objects) throws Throwable { System.out.println(method.getClass()+" start "); return method.invoke(new Hello(),args); } } ); hello.sayHello(); }
三、AOP原理
AOP原理就是使用动态代理
1.对于实现接口的目标类,使用JDK动态代理
2.对于没有实现接口的目标类可以使用cglib技术