1.关于Springboot中AOP说明
2.关于springboot中原生AOP说明
Spring 整合AspectJ框架实现AOP只是Spring框架中AOP的一种实现方式,此方式相对比较简单,实现方便。但此方式底层还是要转换为Spring原生AOP的实现,Spring AOP原生方式实现的核心有两大部分构成,分别是:
▪ 代理(JDK,CGLIB)。
▪ org.aopalliance包下的拦截体系。
其中DefaultAdvisorAutoProxyCreator这个类功能更为强大,这个类的奇妙之处是他实现BeanPostProcessor接口,当ApplicationContext读取所有的Bean配置信息后,这个类将扫描上下文,寻找所有的Advisor对象(一个Advisor由切入点和通知组成),将这些Advisor应用到所有符合切入点的Bean中。
3.关于springboot中原生AOP实现demo
3.1 自定义注解RequireCache
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequireCache {
String value() default "";
}
3.2 编写advice类
public class CacheAdvice implements MethodInterceptor {
Map<String,Object> map = new ConcurrentHashMap<String,Object>();
/**
* 通过反射拿到类上面的注解,判断注解是否为RequireCache,
*
* @param invocation
* @return
* @throws Throwable
*/
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Class<?> aClass1 = invocation.getThis().getClass();
Method declaredMethod = aClass1.getDeclaredMethod(invocation.getMethod().getName(), invocation.getMethod().getParameterTypes());
RequireCache annotation =declaredMethod.getAnnotation(RequireCache.class);
if (annotation!=null){
Object list =map.get(annotation.value());
if (list!=null){
return list;
}
}
Object proceed = invocation.proceed();
map.put(annotation.value(),proceed);
return proceed;
}
}
3.3 编写advisor类
@Component
public class CacheAdvisor extends StaticMethodMatcherPointcutAdvisor {
public CacheAdvisor(){
setAdvice(new CacheAdvice());
}
@Override
public boolean matches(Method method, Class<?> targetClass) {
try {
Method declaredMethod = targetClass.getDeclaredMethod(method.getName(), method.getParameterTypes());
RequireCache annotation = declaredMethod.getAnnotation(RequireCache.class);
if (annotation!=null){
return true;
}
}catch (Exception e){
}
return false;
}
}
3.4 编写配置类
@Configuration
public class AdvisorConfig {
@Bean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
return new DefaultAdvisorAutoProxyCreator();
}
}