1.pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
</dependencies>
2.配置配置类
@Configuration
@ComponentScan("top.chenyp")
@EnableAspectJAutoProxy
public class SpringConfig {}
3.配置aspect切入类
package top.chenyp.component.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.util.Date;
@Aspect
@Component
public class MyAspect {
//定义切入点
//使用void返回值,方法体为空的方法来命名切入点
@Pointcut("execution(* top.chenyp.*.*.*(..))")
public void myPointCut() {
}
/**
* 前置通知
*
* @param joinPoint
* @throws Throwable
*/
@Before("myPointCut()")
public void beforelog(JoinPoint joinPoint) throws Throwable {
System.out.println("前置通知方法");
}
/**
* 后置通知
*
* @param joinPoint
* @throws Throwable
*/
@AfterReturning("myPointCut()")
public void afterlog(JoinPoint joinPoint) throws Throwable {
System.out.println("后置通知方法");
}
/**
* 环绕事务
*/
@Around("myPointCut()")
public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("模拟开启事务");
long time1 = new Date().getTime();
System.out.println("开始时间:" + time1);
Object proceed = joinPoint.proceed();
long time2 = new Date().getTime();
System.out.println("关闭时间:" + time2);
System.out.println("模拟关闭事务");
long time3 = time2 - time1;
System.out.println("方法执行的时间为: " + time3 + "ms");
return proceed;
}
/**
* 异常通知
*/
@AfterThrowing(value = "myPointCut()",throwing = "e")
public void afterThrowing(JoinPoint joinPoint, Throwable e) {
System.out.println("异常通知:" + e.getMessage());
}
/**
* 最终通知
*/
@After("myPointCut()")
public void myAfter() {
System.out.println("最终通知: 模拟释放资源");
}
}
4.配置service写一个方法
@Service
public class UserServiceImpl implements UserService {
@Override
public void printfUser() {
System.out.println("打印用户的信息");
}
}
5.测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class Test {
@Autowired
private UserService service;
@org.junit.Test
public void test(){
service.printfUser();
}
}