首页 > 代码库 > aop实现
aop实现
****
1,使用动态代理实现aop
public interface UserDao { void save();}public class UserDaoImpl implements UserDao { private String name; public void save() { System.out.println("save() is called, name: "+name); } public String getName() { return name; } public void setName(String name) { this.name = name; } }
ProxyFactory.java
package com.maple.util;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;import com.maple.dao.UserDao;import com.maple.dao.impl.UserDaoImpl;public class ProxyFactory implements InvocationHandler { private Object target; public Object createUserDao(Object target){ this.target=target; return Proxy.newProxyInstance(this.target.getClass().getClassLoader(), this.target.getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println(proxy.getClass().getName()); Object result=null; UserDaoImpl userDao=(UserDaoImpl)this.target; if(userDao.getName()!=null){ result=method.invoke(userDao, args); }else{ System.out.println("the name is null"); } return result; }}
测试
@Test public void test() { ProxyFactory pf=new ProxyFactory(); UserDaoImpl u=new UserDaoImpl(); u.setName("maple"); UserDao userDao=(UserDao) pf.createUserDao(u); userDao.save(); }
输出:
$Proxy5
save() is called, name: maple
****
aop实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。