使用Spring的原生接口
准备环境:
约束
xmlns:aop="http://www.springframework.org/schema/aop"
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
jar包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
- 要插入的类实现接口MethodBeforeAdvice(前置通知),AfterReturningAdvice(后置通知),MethodInterceptor(环绕通知)。
public class AfterLog implements AfterReturningAdvice {
@Override
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println(o1.getClass().getName()+"的"+method.getName()+"被执行了,返回结果是"+o);
}
}
public class BeforeLog implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(o.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
- 在applicationcontext中注册
<aop:config>
<aop:pointcut id="pointCut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointCut"/>
<aop:advisor advice-ref="beforeLog" pointcut-ref="pointCut"/>
</aop:config>
这里的execution中第一个*为返回值类型。第二个表示所有方法。括号…表示任何参数。
- 测试
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserService userService = context.getBean("userService", UserService.class);
User user = context.getBean("user",User.class);
People people = context.getBean("people",People.class);
people.getDog().shot();
people.getCat().shot();
userService.select();
user.setName("123");
System.out.println(user.getName());
}
}
返回值是接口类
- 结果
第二种方式:使用自定义类实现
- 编写自定义类
- 注册bean
- 选择切面并插入
<aop:config>
<aop:aspect ref="diy" >
<aop:pointcut id="point" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
<aop:before method="before" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
第三种方式:使用注解实现
- 编写类,在类名上添加@Aspect注解
- 编写方法,在方法名上添加@After,@Before等注解,并在之后加入execution方法。
- 在配置文件中开启
<aop:aspectj-autoproxy/>
@Aspect
@Component
public class AnnotationPointCut {
@After("execution(* com.kuang.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("方法执行后");
}
@Before("execution(* com.kuang.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("方法执行前");
}
@Around("execution(* com.kuang.service.UserServiceImpl.*(..))")
public void round(ProceedingJoinPoint jp) throws Throwable{
System.out.println("环绕前");
Object proceed = jp.proceed();
System.out.println("环绕后");
}
}