面向切面编程,通过预编译的方式,和运行期动态代理实现程序功能的统一维护的一种技术。
使用AOP织入,需要导入一个依赖包
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency>
加入日志
方式一:log实现MethodBeforeAdvice
public class Log implements MethodBeforeAdvice { //method--要执行的目标对象的方法 //object--参数 //target--目标对象 public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了"); } }
public class AfterLog implements AfterReturningAdvice { //returnValue:返回值 public void afterReturning(Object returnValue, Method method, Object[] objects, Object o1) throws Throwable { System.out.println("执行了"+method.getName()+"方法,返回值为:"+returnValue); } }
配置AOP 导入约束
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <!--注册bean--> <bean id="afterlog" class="com.wang.service.AfterLog"/> <bean id="log" class="com.wang.service.Log"/> <bean id="userservice" class="com.wang.service.UserServiceImpl"/> <!--方式一:使用原生SpringApi--> <!--配置AOP;导入约束--> <aop:config> <!--切入点:express:表达式 execution(要执行的位置 *****)--> <aop:pointcut id="pointcut" expression="execution(* com.wang.service.UserServiceImpl.*(..))"/> <!--执行环绕增加--> <aop:advisor advice-ref="log" pointcut-ref="pointcut"/> <aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/> </aop:config> </beans>
方式二:自定义实现AOP {切面定义}
public class DiyLog { public void before(){ System.out.println("开始前"); } public void after(){ System.out.println("开始后"); } }
<!--方式二--> <bean id="diyLog" class="com.wang.service.diy.DiyLog"/> <aop:config> <!--自定义切面,ref要引用的类--> <aop:aspect ref="diyLog"> <!--切入点--> <aop:pointcut id="point" expression="execution(* com.wang.service.UserServiceImpl.*(..))"/> <aop:before method="before" pointcut-ref = "point"/> <aop:after method="after" pointcut-ref="point"/> </aop:aspect> </aop:config>
方式三:使用注解实现
@Aspect//标注这个类是一个切面 public class AnnotationPointCut { @Before("execution(* com.wang.service.UserServiceImpl.*(..))") public void before(){ System.out.println("方法前使用");------2 } @After("execution(* com.wang.service.UserServiceImpl.*(..))") public void after(){ System.out.println("方法后使用");------4 } //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点 @Around("execution(* com.wang.service.UserServiceImpl.*(..))") public void around(ProceedingJoinPoint jp) throws Throwable{ System.out.println("环绕前");------1 Object proceed = jp.proceed();//执行方法 System.out.println("环绕后");------3 } }
<!--方式三--> <bean id="annotationPointCut" class="com.wang.service.diy.AnnotationPointCut"/> <!--开启注解支持 JDK(默认proxy-target-class="false") cglib(proxy-target-class="true")--> <aop:aspectj-autoproxy/>