1、搭建好框架,本例基于SSH创建,导入包aspectjrt.jar、aspectjweaver.jar
2、定义切面类,定义切面方法,(方法:@Before、@After、@Around、@AfterReturning)
Action类
public String checklogin(){
System.out.println("FirstTestAction methods checklogin");
HttpServletRequest request = ServletActionContext.getRequest();
System.out.println("Action 用户id="+(String)request.getParameter("userIdStr"));
String returnValue = firstTestService.checkLogin((String)request.getParameter("userIdStr"));
System.out.println("最终返回值="+returnValue);
return SUCCESS;
}
Service类
public String checkLogin(String userIdStr) {
System.out.println("Service 用户id="+userIdStr);
System.out.println("FirstTestServiceImpl methods checkLogin");
firstTestDao.checkLogin(userIdStr);
return "旧的返回值";
}
Advice类
package com.test.testAction;
import java.util.Arrays;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class AdviceTest {
//匹配test.testServices.impl包下所有类中所有方法的执行作为切入点
@Before("execution(* com.test.testServices.impl.*.*(..))")
public void beforeMethod(){
System.out.println("方法前执行。。。。。");
}
@Around(value = "execution(* com.test.testServices.impl.*.*(..))")
public Object aroundMethod(ProceedingJoinPoint jp) throws Throwable{
System.out.println("********Around start...");
jp.proceed(new String[]{"20271482"});//不调用jp.proceed()不执行方法,有参数改变被切面方法参数
System.out.println("被Advice方法名jp.getSignature().getName():"+jp.getSignature().getName());
System.out.println("被Advice类名jp.getTarget():"+jp.getTarget());
System.out.println("被Advice参数jp.getArgs():"+Arrays.toString(jp.getArgs()));
System.out.println("被Advice详细信息jp.getStaticPart():"+jp.getStaticPart());
System.out.println("jp源码类jp.getSourceLocation():"+jp.getSourceLocation());
System.out.println("********Around end...");
return "新的返回值";//改变被切面方法返回值
}
}
3、配置applicationContext.xml文件,增加切面配置
注:
1)配置文件需配置spring aop 头文件,需包括如下
xmlns:aop="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
2)切记将切面类注入,防止aspectj失效
4、被切面的类无需做任何处理
5、启动项目,运行被切面类的方法时成功
运行结果:切面方法在Action方法执行之后执行,在serviceImpl类中方法执行之前执行
FirstTestAction methods checklogin
Action 用户id=20502192
方法前执行。。。。。
********Around start...
Service 用户id=20271482
FirstTestServiceImpl methods checkLogin
FirstTestDaoImpl method checkLogin..
被Advice方法名jp.getSignature().getName():checkLogin
被Advice类名jp.getTarget():com.test.testServices.impl.FirstTestServiceImpl@2792e317
被Advice参数jp.getArgs():[20271482]
被Advice详细信息jp.getStaticPart():execution(String com.test.testServices.FirstTestService.checkLogin(String))
jp源码类jp.getSourceLocation():org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint$SourceLocationImpl@7e91259
********Around end...
最终返回值=新的返回值