a simple example for spring AOP

渣渣演發表於2016-03-28
/**
* Created by Administrator on 2015/11/25.
* a interface
*/
public interface ArithmeticCalculator{
int add(int i, int j);
int sub(int i, int j);
int mul(int i, int j);
int div(int i, int j);
}



public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
public ArithmeticCalculatorImpl(){}//無引數構造器
@Override
public int add(int i, int j) {
int result=i+j;
return result;
}

@Override
public int sub(int i, int j) {
int result=i-j;
return result;
}

@Override
public int mul(int i, int j) {
int result=i*j;
return result;
}

@Override
public int div(int i, int j) {
int result=i/j;
return result;
}
}



public class LoggingAspect {
//前置通知。
public void beforeMethod(JoinPoint joinPoint){
String methodname=joinPoint.getSignature().getName();
List<Object> args= Arrays.asList(joinPoint.getArgs());
System.out.println("The Method name is "+methodname+" args is:"+args);
}

//後置通知。
public void AfterMethod(JoinPoint joinPoint){
String methodname=joinPoint.getSignature().getName();
System.out.println("The Method "+methodname+" ends!");
}

//返回通知,可以訪問到方法的返回值。
public void afterReturning(JoinPoint joinPoint,Object result){
String methodname=joinPoint.getSignature().getName();
System.out.println("The Method "+methodname+" end with:"+result);
}

//異常通知
public void afterThrowing(JoinPoint joinPoint,Exception e){
String methodname=joinPoint.getSignature().getName();
System.out.println("The Method "+methodname+" occurs excetion:"+e);
}
}



public class Main {
public static void main(String[]args){
//貌似java的自動代理機制只能代理介面裡面的方法。有待驗證。AOP好像也只能代理介面裡面的方法
//java的動態代理是要代理一大堆類,用類你怎麼實現這個功能呢
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
//不明白為什麼一定要用介面來接受bean的例項,換了實現類會跑異常
ArithmeticCalculator arithmeticCalculator=(ArithmeticCalculator)ctx.getBean("arithmeticCalculatorImpl");
arithmeticCalculator.add(100, 20);
arithmeticCalculator.div(9, 3);
}
}


spring裡面的配置如下:
<!--配置一個普通的bean-->
<bean id="arithmeticCalculatorImpl" class="Spring_AOP.Aophelloworld.ArithmeticCalculatorImpl"></bean>

<!--配置一個普通的bean-->
<bean id="loggingAspect" class="Spring_AOP.Aophelloworld.LoggingAspect"></bean>

<!--配置Aop資訊-->
<aop:config>
<!--配置切面表示式-->
<!--第一個*是public int 表示任意返回型別,接著是全類名.方法(int,int),這裡第二個*表示
所有的方法,(..)表示任意型別的引數-->
<aop:pointcut id="pointcut" expression="execution(* Spring_AOP.Aophelloworld.ArithmeticCalculator.*(..))"/>
<!--配置切面通知-->
<aop:aspect ref="loggingAspect" order="1"><!--order用來配置切面優先順序-->
<aop:before method="beforeMethod" pointcut-ref="pointcut"/>
<aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/>
<aop:after method="AfterMethod" pointcut-ref="pointcut"/>
<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="e"/>
</aop:aspect>
</aop:config>