利用AOP实现自定义注解

2017-12-19  本文已影响11人  若尘0328

1.加入pom依赖

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.6.12</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.12</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2</version>
        </dependency>

2.spring的配置文件中加入配置

<context:component-scan base-package="com.yonyou.annotation"/>
<aop:aspectj-autoproxy proxy-target-class="true"/>

3.编写自定义注解

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Mycache {
    String key();//缓存键值

    String cacheName();//缓存名称

    String backupName() default "";//备份缓存的名字

    boolean needBloomFilter() default false;//是否需要布隆过滤器

    boolean needLock() default false;//是否加上分布式锁
}

4.编写切面

@Aspect
@Component
public class CacheAspect {
     //环绕增强,去切带有Mycache 注解的方法
    @Around("@annotation(mycache)")
    public Object doAround(ProceedingJoinPoint pjp,Mycache mycache){
        try {
            //获得形式参数名
            Method method = ((MethodSignature) pjp.getSignature()).getMethod();
            String[] parameterNames = new LocalVariableTableParameterNameDiscoverer().getParameterNames(method);
            //使用el表达式
            String key = ElParser.parse(mycache.key(), parameterNames, pjp.getArgs());
            System.out.println(key);
            //执行切点方法
            Object proceed = pjp.proceed();
            System.out.println(mycache.cacheName());
            return proceed;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return null;
        }
    }
}

5.获得el表达式的值的工具类

public class ElParser {
    public static String parse(String key,String [] parseNames,Object [] args){
        ExpressionParser parser=new SpelExpressionParser();
        Expression expression = parser.parseExpression(key);
        EvaluationContext ctx=new StandardEvaluationContext();
        for (int i = 0; i < parseNames.length; i++) {
            ctx.setVariable(parseNames[i],args[i]);
        }
        return (String) expression.getValue(ctx);
    }
}

上一篇下一篇

猜你喜欢

热点阅读