使用Spring AOP实现日记记录
1. 加入Jar包
<span style="font-size:18px;">2. 目标方法
packagecom.datatub.service;
publicclass LoginService {
private String name;
public String login(String name){
System.out.println("Hello"+name);
return "ok";
}
}
3. 前置通知,后置通知
packagecom.datatub.log;
importorg.aspectj.lang.JoinPoint;
publicclass LogDetail {
//在类里面写方法,方法名可以任意。标准用的before和after来表示
//此处的JoinPoint类可以获取,action所有的相关配置信息和request等内置对象。
public void before(JoinPoint joinpoint){
Object[]obj = joinpoint.getArgs();//此方法返回的是一个数组,数组中包括request以及ActionCofig等类对象
System.out.println("调用的方法名:"+joinpoint.getSignature().getName());
System.out.println("调用的方法参数:"+joinpoint.getArgs()[0]);
}
public void after(JoinPoint joinpoint){
Object[] obj = joinpoint.getArgs();
System.out.println("调用的方法:"+joinpoint.getSignature().getName()+"调用完毕");
}
}
4. 配置SPRING.XML文件
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<context:component-scanbase-package="com.datatub.service.*" />
<bean id="loginServ"class="com.datatub.service.LoginService"></bean>
<bean id="loginServ2"class="com.datatub.service2.LoginService2"></bean>
<bean id="logDetail"class="com.datatub.log.LogDetail"></bean>
<aop:config>
<!--配置在com.datatub.service或com.datatub.service2包下所有的类在调用之前都会被拦截-->
<aop:pointcut id="log"expression="(execution(* com.datatub.service.*.*(..))) or (execution(*com.datatub.service2.*.*(..)))"/>
<aop:aspect id="aspect"ref="logDetail">
<!--在log包下面所有的类的所有方法被调用之前都调用LogDetail中的before方法-->
<aop:beforepointcut-ref="log" method="before"/>
<!--在log包下面所有的类的所有方法被调用之前都调用LogDetail中的after方法-->
<aop:afterpointcut-ref="log" method="after"/>
</aop:aspect>
</aop:config>
</beans>
5. 测试
packagecom.datatub.test;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
importcom.datatub.service.LoginService;
importcom.datatub.service2.LoginService2;
publicclass Test {
public static void main(String[] args) {
ApplicationContext app=newClassPathXmlApplicationContext("applicationContext.xml");
LoginServiceloginServ = (LoginService) app.getBean("loginServ");
LoginService2 loginServ2 =(LoginService2) app.getBean("loginServ2");
loginServ.login("datatub");
loginServ2.login("datatub2");
}
}
6.运行结果 </span>