1.创建一个简单的SpringBoot应用,然后在pom文件中引入spring-boot-start-aop.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.编写一个AOP切面类:
package com.jinyu.springboot.config;
import java.util.Arrays;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;
@Configuration
@Aspect
public class AOPConfig {
@Around("@within(org.springframework.stereotype.Controller)")
public Object simpleAop(final ProceedingJoinPoint pjp) {
Object[] args = pjp.getArgs();
System.out.println("args:"+Arrays.asList(args));
//调用原有的方法
Object o = null;
try {
o = pjp.proceed();
System.out.println("return:"+o);
} catch (Throwable e) {
e.printStackTrace();
}
return o;
}
}
package com.jinyu.springboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloWorldController {
@RequestMapping("/hello.do")
public @ResponseBody String say(String name) {
return "Hello Spring Boot";
}
}
输入http://localhost:8080/hello.do?name=aaa的时候,查看控制台,会发现有如下输出:
SpringAOP支持多种表达式及表达式的组合,例如:
execution(public **(..)):所有public方法,后面的星号代表类路径和方法名。
execution(* set*(..)):所有set开头的方法。
execution(public set*(..)):所有set开头的public方法。
execution(public com.xyz.service.* set*(..)):所有set开头的public方法,且位于com.xyz.service包下。
target(com.xyz.service.CommonService):所有实现了CommonService借口的类的方法。
@target(org.springframework.transaction.annotation.Transactional):所有用@Transactional注解的方法。
@within(org.springframework.stereotype.Controller):类型声明了@Controller注解的所有方法。