配置AOP
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Service层
@Service
public class UserService {
public String getUsernameById(Integer id){
System.out.println("getUsernameById");
return "java";
}
public void deleteUserById(Integer id){
System.out.println("deleteUserById");
}
}
Controller层
@RestController
public class UserController {
@Autowired
UserService userService;
@GetMapping("/test1")
public String getUsernameById(Integer id){
return userService.getUsernameById(id);
}
@GetMapping("/test2")
public void deleteUserById(Integer id){
userService.deleteUserById(id);
}
}
@Component
@Aspect
public class LogComponent {
//返回值任意 以com.qwl.myaop.service下所有的方法
@Pointcut("execution(* com.qwl.myaop.service.*.*(..))")
public void pc1(){
}
@Before(value = "pc1()")
public void before(JoinPoint jp){
String name= jp.getSignature().getName();
System.out.println("before--"+name);
}
@After(value = "pc1()")
public void after(JoinPoint jp){
String name = jp.getSignature().getName();
System.out.println("after--"+name);
}
@AfterReturning(value = "pc1()",returning="result")
public void afterReturning(JoinPoint jp,Object result){
String name=jp.getSignature().getName();
System.out.println("afterReturning---"+name+"--------"+result);
}
@AfterThrowing(value = "pc1()",throwing = "e")
public void afterThrowing(JoinPoint jp,Exception e){
String name=jp.getSignature().getName();
System.out.println("afterThrowing---"+name+"--------"+e.getMessage());
}
@Around("pc1()")
public Object around(ProceedingJoinPoint pjp)throws Throwable{
Object proceed = pjp.proceed();
return "java 技术";
}
}