简介
面向切面编程,编程的关注点是一个横切面
实现过程
额外补充依赖
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.3</version>
</dependency>
配置文件 applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--AOP是基于代理完成的,所以要激活自动代理-->
<aop:aspectj-autoproxy/>
<!--注册一个切面要使用的类-->
<bean class="com.cyk.advice.BeforceAdvice" id="beforceAdvice">
</bean>
<bean class="com.cyk.service.ProviderService" id="providerService">
</bean>
<!--配置切入点等信息-->
<aop:config>
<aop:aspect id="beforeAspect" ref="beforceAdvice">
<!--aop:before 表明使用前置通知
method指明它用哪个方法来切
poincut切入点 路径名+方法名
-->
<!--如果有多个同类型的建议,谁在前谁先执行-->
<aop:before method="methodBefore" pointcut="execution(* com.cyk.service.*.*(..))"/>
<aop:before method="before" pointcut="execution(* com.cyk.service.*.*(..))"/>
</aop:aspect>
</aop:config>
</beans>
</beans>
使用returning对返回值进行绑定
public void afterReturning(String returning){
System.out.println("返回值是:"+ returning);
}
<bean class="com.cyk.advice.AfterReturningAdvice" id="afterReturningAdvice">
</bean>
<aop:aspect ref="afterReturningAdvice">
<aop:after-returning method="afterReturning" pointcut="execution(* com.cyk.service.*.*(..))" returning="returning"/>
</aop:aspect>
ExceptionAdvice
public void exe(){
System.out.println("执行exe");
throw new RuntimeException("我故意的")
}
<bean class="com.cyk.advice.ExceptionAdvice" id="exceptionAdvice">
</bean>
<aop:aspect ref="exceptionAdvice">
<aop:after-throwing method="excep" pointcut="execution(* com.cyk.service.*.*(..))"/>
</aop:aspect>
AroundAdvice
- 既可以在目标方法之前织入增强动作,也可以在执行目标方法之后织入增强动作;
- 它可以决定目标方法在什么时候执行,如何执行,甚至可以完全阻止目标目标方法的执行;
- 它可以改变执行目标方法的参数值,也可以改变执行目标方法之后的返回值;
- 当需要改变目标方法的返回值时,只能使用Around方法;
虽然Around功能强大,但通常需要在线程安全的环境下使用。因此,如果使用普通的Before、AfterReturing增强方法就可以解决的事情,就没有必要使用Around增强处理了。
public Object around(ProceedingJoinPoint pjp) {
try {
System.out.println("环绕地球80天。。。。。。。。。。。。。。。。。。。。。");
Object proceed = pjp.proceed();
return proceed;
} catch (Throwable throwable) {
throwable.printStackTrace();
return null;
}
}
<bean class="com.cyk.advice.AroundAdvice" id="aroundAdvice">
</bean>
<aop:aspect ref="aroundAdvice">
<aop:around method="around" pointcut="execution(* com.cyk.service.*.*(..))"/>
</aop:aspect>