1.建立了日志类
package cn.edu.proxy.cglibproxy; public class Logger { public void logging() { // TODO Auto-generated method stub System.out.println("logging"); } }
2.建立安全类
package cn.edu.proxy.cglibproxy; public class Security { public void security() { // TODO Auto-generated method stub System.out.println("security"); } }
3.建立权限类
package cn.edu.proxy.cglibproxy; public class Privilege { private String access; public String getAccess() { return access; } public void setAccess(String access) { this.access = access; } }
4.建立薪水管理接口
package cn.edu.proxy.cglibproxy; public interface SalaryManager { public void showSalary(); }
5.建立薪水管理类的实现
package cn.edu.proxy.cglibproxy; public class SalaryManagerImpl implements SalaryManager { @Override public void showSalary() { // TODO Auto-generated method stub System.out.println("查看工资"); } }
6.建立拦截器类,并且把其他的类以构造函数的形式导入,此类实现了InvocationHandler接口,其中Object是目标类
如果满足access为admin就执行方法,否则就输出没有权限
package cn.edu.proxy.cglibproxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class SalaryInterceptor implements InvocationHandler{ private Object target; private Logger logger; private Security security; private Privilege privilege; public SalaryInterceptor(Object target, Logger logger, Security security, Privilege privilege) { super(); this.target= target; this.logger = logger; this.security = security; this.privilege = privilege; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub if(this.privilege.getAccess().equals("admin")){ this.logger.logging(); this.security.security(); method.invoke(this.target, args); }else{ System.out.println("对不起,您没有权限"); } return null; } }
7.建立测试类,建立日志类,安全类,以及权限类的实例,并且建立拦截器类。
使用代理的方法newProxyInstance()返回薪水管理类(这是目标类)
package cn.edu.proxy.cglibproxy; import java.lang.reflect.Proxy; import org.junit.Test; public class SalaryTest { @Test public void test(){ Object target=new SalaryManagerImpl();//目标类 Logger logger=new Logger(); Privilege privilege=new Privilege(); privilege.setAccess("admin"); Security security=new Security(); SalaryInterceptor interceptor=new SalaryInterceptor(target, logger, security, privilege); SalaryManager salaryManager=(SalaryManager)Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), interceptor); salaryManager.showSalary(); } }
总结:
aop:
1.切面
日志,安全类框架,权限等都是切面
2.通知
切面中的方法就是通知
3.目标类
4.切入点
5.织入
形成代理对象的方法的过程
好处:
日志,安全性框架,权限,目标方法之间完全是松耦合的
时间: 2024-10-21 05:42:26