Aop 面向切面
Aop在Spring中的使用流程
添加依赖spring-aspect
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
编写切面类
//@Component 将切面类交给spring容器管理
//@Aspect 让spring识别出为切面类,区别与其他非切面类
@Component
@Aspect
public class MyAspect {
//配置值切点,使用execution表达式 方法的名称为切点的名称
//spring.aop下的所有类的所有方法,具体参照execution表达式
@Pointcut("execution( * spring.aop..*.*(..))")
public void myPointCut(){
}
@Before("spring.aop.aspect.MyAspect.myPointCut()")
public void beforeFunc(){
System.out.println("前置通知");
}
@After("execution( * spring.aop..*.*(..))")
public void afterFunc(){
System.out.println("后置通知");
}
@AfterReturning("myPointCut()")
public void afterReturningFunc(){
System.out.println("返回通知");
}
@AfterThrowing("myPointCut()")
public void afterThrowingFunc(){
System.out.println("异常通知");
}
@Around("myPointCut()")
public void aroundFunc(ProceedingJoinPoint proceedingJoinPoint){
System.out.println("环绕通知");
Object[] args = proceedingJoinPoint.getArgs();
for (Object o:args) {
System.out.print(o+" - ");
}
System.out.println("环绕结束");
}
}
spring开启切面功能
//配置类
@Configuration
@ComponentScan(value = {"spring.aop.dao"})
@Import(value = {MyAspect.class})
@EnableAspectJAutoProxy
public class MySpringAopConfig {
}
// 作用的切点
@Repository
public class AppleDao {
public void aVoid(){
System.out.println("执行了aVoid()");
}
public void bVoid(String a,String b,String c) throws Exception {
if("xyz".equals(c)){
throw new Exception();
}
System.out.println("执行了bVoid()");
}
}
//测试类的测试方法
@Test
public void test() throws Exception {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MySpringAopConfig.class);
AppleDao appleDao= applicationContext.getBean("appleDao", AppleDao.class);
appleDao.aVoid();
System.out.println("++++++++++++++++++++");
appleDao.bVoid("1", "2", "xyz");
}
切面类中的advice的执行顺序
参考博客:https://blog.csdn.net/rainbow...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。