新建UserService类
package org.hx.springboot_aop_demo24.service;
import org.springframework.stereotype.Service;
@Service
public class UserService {
public String getUserById(Integer id){
System.out.println("getUserById");
return "user";
}
public void deleteUserById(Integer id){
System.out.println("delete id: "+id);
}
}
新建LogAspect类
package org.hx.springboot_aop_demo24;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class LogAspect {
@Pointcut("execution(* org.hx.springboot_aop_demo24.service.*.*(..))")
public void pointMethod(){
}
@Before("pointMethod()")
public void before(JoinPoint joinPoint)
{
String name = joinPoint.getSignature().getName();
System.out.println("方法开始执行了");
}
@After("pointMethod()")
public void after(JoinPoint joinPoint)
{
String name = joinPoint.getSignature().getName();
System.out.println("方法执行结束了。。。");
}
@AfterReturning(value = "pointMethod()",returning = "s")
public void afterReturning(JoinPoint joinPoint,String s){
String name = joinPoint.getSignature().getName();
System.out.println(name+"方法返回值是: "+s);
}
@AfterThrowing(value = "pointMethod()",throwing = "e")
public void afterthrowing(JoinPoint joinPoint,Exception e)
{
String name = joinPoint.getSignature().getName();
System.out.println(name+"方法抛出了异常"+e.getMessage());
}
@Around("pointMethod()")
public Object around(ProceedingJoinPoint proceedingJoinPoint){
try {
Object proceed = proceedingJoinPoint.proceed();
return proceed;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return null;
}
}
在单元测试类中进行测试
package org.hx.springboot_aop_demo24;
import org.hx.springboot_aop_demo24.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringbootAopDemo24ApplicationTests {
@Autowired
UserService userService;
@Test
void contextLoads() {
userService.getUserById(99);
}
}