依赖
在pom中添加一下依赖:
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.1</version>
</dependency>
步骤
在这里我们把打印日志做一个切面。
关于AOP的理解可以看:https://blog.youkuaiyun.com/q982151756/article/details/80513340
1. 添加Configation类开启AOP的自动代理。
@Configuration
@EnableAspectJAutoProxy
public class LogConfigation {
}
@EnableAspectJAutoProxy这个注解就是开启AOP的自动代理。
2. 写一个注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LogAnnotation {
String value() default "";
}
该注解表示生命周期是运行时也保存,且作用于方法。
关于注解可以看:https://blog.youkuaiyun.com/jgnewbie/article/details/78401691
3. 写我们的切面
@Component
@Aspect
public class LogAspect {
//表示只要加了注解LogAnnotation的方法都是要织入的点
@Pointcut("@annotation(com.study.mystudy.log.annotation.LogAnnotation)")
public void logAspect() {
}
//在使用了注解LogAnnotation的方法执行之前执行beforeMethod
@Before("logAspect()")
public void beforeMethod(JoinPoint joinPoint){
System.out.println("我在前面执行。。。");
System.out.println("方法名:" + joinPoint.getSignature().getName());
System.out.println("类名:" + joinPoint.getSignature().getDeclaringType().getName());
}
}
执行时机大致可分为:之前,之后,环绕,返回通知,异常通知。
JoinPoint作用:JoinPoint对象封装了切点方法的信息,在切面方法中添加JoinPoint参数,就可以获取到封装了该切点方法信息的JoinPoint对象.
方法名 | 功能 |
Signature getSignature(); | 获取封装了署名信息的对象,在该对象中可以获取到目标方法名,所属类的Class等信息 |
Object[] getArgs(); | 获取传入目标方法的参数对象 |
Object getTarget(); | 获取被代理的对象 |
Object getThis(); | 获取代理对象 |
4. 在我们的Service中的某个方法中加入注解:
@Service
public class HelloServiceImpl implements HelloService {
@Override
@LogAnnotation
public String getHello() {
System.out.println("hello");
return "hello";
}
}
注意:HelloSrviceImpl需要在Spring容器中,此处加了@Service注解,已经加入到了Spring容器中,否则不起作用。
5. 当前端访问某个资源时,调用了我们的getHello方法,AOP就会其中用。
我们总结一下:
注解 | 解释 |
@Before | 在被代理对象的方法前先调用 |
@Around | 将被代理对象的方法封装起来,用环绕通知取代他 |
@After | 在被代理对象的方法后调用 |
@AfterReturning | 在被代理对象的方法正常返回后调用 |
@AfterThrowing | 在被代理对象的方法抛出异常后调用 |