Springboot中原生AOP实现说明

1.关于Springboot中AOP说明

关于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();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值