需求1-日志:在程序执行期间追踪正在发生的活动;
需求2-验证:希望计算器只处理正数的运算;
一、普通方法实现
Calculator.java
package com.gong.spring.aop.helloworld; public interface Calculator { int add(int i,int j); int sub(int mul(int div( j); }
CalculatorImpl.java
class CalculatorImpl implements Calculator{ @Override j) { System.out.println("add begin"); // Todo Auto-generated method stub int result = i+j; System.out.println("add end"return result; } @Override j) { System.out.println("sub begin"int result = i - j; System.out.println("sub end" j) { System.out.println("mul begin"int result = i * j; System.out.println("mul end" j) { System.out.println("div begin"int result = i / j; System.out.println("div end" result; } }
Main.java
class Main { static void main(String[] args) { Calculator calculator = new CalculatorImpl(); int i = 2; int j = 1int res = calculator.add(i,j); System.out.println(res); res = calculator.sub(i,1)"> calculator.mul(i,1)"> calculator.div(i,j); System.out.println(res); } }
输出:
存在两个问题:
(1)代码混乱:每个方法在处理逻辑核心问题时还要关注其它问题,比如日志和计算。
(2)代码分散:如果日志发生变化,则需要修改所有方法的日志。
二、第一种解决方法:使用动态代理。
动态代理原理:使用一个代理将对象包装起来,然后调用该代理对象取代原始对象,任何对原始对象的调用都要通过代理。代理对象决定是否以及何时将方法转到原始的对象上。
CalculatorLoggingImpl.java
class CalculatorLoggingImpl j) { j; j; result; } }
import java.lang.reflect.InvocationHandler; java.lang.reflect.Method; java.lang.reflect.Proxy; CalculatorLoggingProxy { public CalculatorLoggingProxy(Calculator target) { this.target = target; } 要代理的对象 private Calculator target; Calculator getLoggingProxy() { Calculator proxy = null代理对象由哪一个类加载器进行加载 ClassLoader loader = target.getClass().getClassLoader(); 代理对象的类型,即其中有哪些方法 Class [] interfaces = new Class[]{Calculator.}; 调用代理对象其中的方法时,该执行的代码 InvocationHandler h = InvocationHandler() { /*proxy:正在返回的代理对象 *method::正在被调用的方法 *args:调用方法时传入的参数 * */ @Override public Object invoke(Object proxy,Method method,Object[] args) throws Throwable { Todo Auto-generated method stub String methodName = method.getName(); 日志 System.out.println(methodName+" begin"); 执行方法 Object result = method.invoke(target,args); 日志 System.out.println(methodName+" end" result; } }; proxy = (Calculator) Proxy.newProxyInstance(loader,interfaces,h); proxy; } }
Main.java
CalculatorLoggingImpl(); Calculator proxy = CalculatorLoggingProxy(calculator).getLoggingProxy(); int result =proxy.add(i,j); System.out.println(result); result = proxy.sub(i,1)"> proxy.mul(i,1)"> proxy.div(i,j); System.out.println(result); } }
输出:
可以达到同样的效果,但是我们的日志模块只需要关注在代理中如何修改,进而可以影响到普通实现的所有方法。
三、第二种方式:使用AOP
AOP是对传统OOP(面向对象编程)的一种补充。其主要编程对象是切面,而切面模块化横切关注点。在应用AOP时,仍然需要定义公共功能,但可以明确定义这个功能在哪里,以什么方式应用。并且不必修改受影响的类,这样一来横切关注点就被模块化到特殊对象(切面)里。
新建一个包,目录结构如下:
需要加入到build path中的包:
Calculator.java
com.gong.spring.aop.impl; org.springframework.stereotype.Component; @Component result; } }
applicationContext.java
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> context:component-scan base-package="com.gong.spring.aop.impl"></context:component-scan> <!-- 使AspectJ注解起作用:自动为匹配的类生成代理对象 --> aop:aspectj-autoproxy> </beans>
在LoggingAspect.java中先只定义这么一个类,并且加上注解:
java.util.Arrays; java.util.List; javax.management.RuntimeErrorException; org.aspectj.lang.JoinPoint; org.aspectj.lang.ProceedingJoinPoint; org.aspectj.lang.annotation.After; org.aspectj.lang.annotation.AfterReturning; org.aspectj.lang.annotation.AfterThrowing; org.aspectj.lang.annotation.Around; org.aspectj.lang.annotation.Aspect; org.aspectj.lang.annotation.Before; org.springframework.stereotype.Component; 把这个类声明为一个切面:需要把该类放入到IOC容器中,再声明为一个切面 @Aspect @Component LoggingAspect { }
Main.java(这里只测试两个)
org.springframework.context.ApplicationContext; org.springframework.context.support.ClasspathXmlApplicationContext; main(String[] args) { ApplicationContext ctx = new ClasspathXmlApplicationContext("applicationContext.xml"从IOC容器中获取bean的实例 Calculator calculator = (Calculator) ctx.getBean(Calculator.int res = calculator.add(2,1); System.out.println("在主函数中加法计算的结果="+res); res = calculator.div(2,1)">); System.out.println("在主函数中除法计算的结果="+res); } }
1.前置通知
在applicationContext.java中先加入:
声明该方法为一个前置通知,在目标方法之前执行 @Before("execution(public int com.gong.spring.aop.impl.Calculator.*(int,int))") beforeMethod(JoinPoint joinPoint) { String methodName = joinPoint.getSignature().getName(); List<Object> args = Arrays.asList(joinPoint.getArgs()); System.out.println(methodName+" begin with "+args); }
输出:
2.后置通知
再加入:
后置通知:在目标方法执行后,无论是否发生异常,执行的通知 在后置通知中不能访问目标的执行结果 @After("execution(public int com.gong.spring.aop.impl.Calculator.*(int,1)"> afterMethod(JoinPoint joinPoint) { 获取名字 String methodName = joinPoint.getSignature().getName(); 获取参数 List<Object> args = Arrays.asList(joinPoint.getArgs()); System.out.println(methodName+" end with "+args); }
输出:
后置通知在目标函数执行后执行,并且无论目标函数是否出现异常,都会执行。 假设将除法分母设置为0,那么结果为:
3.带返回值的后置通知
在方法正常结束后执行的代码 返回通知是可以访问到方法的返回值的 @AfterReturning(value="execution(public int com.gong.spring.aop.impl.Calculator.*(..))",returning="result" afterReturning(JoinPoint joinPoint,Object result) { String methodName = Arrays.asList(joinPoint.getArgs()); System.out.println("在afterReturning得到返回值:"+ result); System.out.println(methodName+" end with "+args); }
输出:
4.当发生异常时才会运行的通知
还有一种当只有发生异常时才会执行该通知:将除法分母变为0
@AfterThrowing(value="execution(public int com.gong.spring.aop.impl.Calculator.*(..))" afterThrowing(JoinPoint joinPoint,Exception ex) { String methodName = joinPoint.getSignature().getName(); System.out.println(methodName+" occurs exception:"+ex); }
输出:
5.环绕通知
@Around(value="execution(public int com.gong.spring.aop.impl.Calculator.*(..))" Object aroundMethod(ProceedingJoinPoint pjd) { Object result = ; String methodName = pjd.getSignature().getName(); 执行目标方法 try { 前置通知 System.out.println(methodName+" begin with "+Arrays.asList(pjd.getArgs())); 执行目标方法 result = pjd.proceed(); 后置通知 System.out.println("在aroundMethod中得到值:"+result); } catch (Throwable e) { Todo Auto-generated catch block 异常通知 System.out.println("the method occurs exception:" + e); throw RuntimeException(e); } 后置通知 System.out.println(methodName+" end with "+Arrays.asList(pjd.getArgs())); result; }
输出:
当然,在环绕通知中也能狗处理异常。
AOP的好处:
(1)每个事物逻辑位于一个位置,代码不分散,便于维护和升级;
(2)业务模块更简洁,只包含核心业务代码;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。