方式一,实现MethodBeforeAdvice,AfterReturningAdvice接口,在applicationContext.xml中注入bean,创建切入点,配置环绕增加,xml需要引入aop约束。
public void before(Method method, Object[] objects, Object o)//目标方法,方法参数,目标类
public void afterReturning(Object o, Method method, Object[] objects, Object o1)//目标方法返回值,目标方法,方法参数,目标类
<aop:config>
<!-- 切入点 execution(返回类型 类.方法名(参数列表))-->
<!--第一个*代表所有类型,第二个*代表类中所有方法,(..)代表任意参数-->
<aop:pointcut id="pointcut" expression="execution(* com.jay.service.UserServiceImpl.*(..))"/>
<!--执行环绕增加-->
<aop:advisor advice-ref="logBefore" pointcut-ref="pointcut"></aop:advisor>
<aop:advisor advice-ref="logAfter" pointcut-ref="pointcut"></aop:advisor>
</aop:config>
方式二,自定义类和方法,方法中无法通过参数自动获取目标类的相关信息
<aop:config>
<aop:aspect ref="log">
<aop:pointcut id="point" expression="execution(* com.jay.service.UserService.*(..))"/>
<aop:before method="before" pointcut-ref="point" />
<aop:after method="after" pointcut-ref="point" />
</aop:aspect>
</aop:config>
方式三,注解实现AOP
package com.jay.service;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class AnnotationPointCut {
@Before("execution(* com.jay.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("前...");
}
@After("execution(* com.jay.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("后...");
}
}
配置:
<!--方式三,注解实现AOP--> <bean id="annotationPointCut" class="com.jay.service.AnnotationPointCut"/> <!--开启注解支持--> <aop:aspectj-autoproxy/>
测试:
@Test
public void test3() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//代理的是一类业务,需要使用接口
UserService m = context.getBean("userService",UserService.class);
m.getUser("jay.x");
}
要引入依赖
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
浙公网安备 33010602011771号