spring_aop的简单应用(加日志)
首先创建三个需要加日志的类和方法
package com.service;
public class ServiceA {
public void addAccount(String account){
System.out.println("添加账户 in ServiceA:"+account);
}
}
package com.service;
public class ServiceB {
public String deposite(int money){
System.out.println("存款 in ServiceB:"+money);
return "some value returned by deposite in ServiceB";
}
}
package com.service;
public class ServiceC {
public void withdraw(int money){
System.out.println("取款 in ServiceC:"+money);
}
}
在创建一个类 写追加的通知 按照aop分为前置后置以及环绕
package com.service;
import org.aspectj.lang.ProceedingJoinPoint;
public class AopInterceptor {
public void before(){
System.out.println("我是一个前置通知!!!!!");
}
public void after(){
System.out.println("我是一个后置通知!!!!!");
}
public void around(ProceedingJoinPoint point){
try {
System.out.println("环绕通知开始!!!");
Object retval = point.proceed();//执行方法
String name = point.getSignature().getName();//获取当前执行的切入点的方法名
System.out.println("方法名:"+name);
Object[] args = point.getArgs();//获取参数
System.out.println("参数:"+args[0]);
System.out.println("环绕通知返回结果:"+retval);
System.out.println("环绕通知结束!!!");
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
xml文件的配置
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="serviceA" class="com.service.ServiceA"></bean>
<bean id="serviceB" class="com.service.ServiceB"></bean>
<bean id="serviceC" class="com.service.ServiceC"></bean>
<bean id="aopInterceptor" class="com.service.AopInterceptor"></bean>
<aop:config>
<!-- 切入点表达式,匹配出的所有方法组成一个切面 -->
<aop:pointcut expression="execution(* com.service.Service*.*(..))" id="allMethod"/>
<aop:pointcut expression="execution(* com.service.ServiceA.*(..))" id="serviceAMethod"/>
<!-- 建立切面和通知的联系 ref指向通知 -->
<aop:aspect ref="aopInterceptor">
<!-- 配置前置通知 method:通知模块中的一个方法(通知) pointcut-ref:切入点表达式-->
<!-- <aop:before method="before" pointcut-ref="allMethod"/>
<aop:after method="after" pointcut-ref="serviceAMethod"/> -->
<!-- 环绕通知 -->
<aop:around method="around" pointcut-ref="allMethod"/>
</aop:aspect>
</aop:config>
</beans>
测试
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.service.ServiceA;
import com.service.ServiceB;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("aop.xml");
ServiceA serviceA = context.getBean("serviceA",ServiceA.class);
serviceA.addAccount("10000");
ServiceB serviceB = context.getBean("serviceB",ServiceB.class);
serviceB.deposite(1000);
}
}
结果