需求是这样的,业务代码需要使用到缓存功能以减少数据库压力,使用redis来实现,并且需要生成缓存的key由方法的传参拼接而成(貌似也只能这样才能保证同样的select查询可以使用缓存),简单的方式就是在需要缓存的方法内加上大概这样的逻辑:查询缓存--->没有则查询数据库 --->查询结果以key-value形式放入缓存,这样对业务代码造成了侵入,并且产生大量重复的代码,很不优雅,所以决定自己封装一个缓存模块,在需要缓存的地方只需要加入一个注解即可。

  首先自定义一个注解

package com.example.test.aspect;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface MyCache { String value() default "";
}

  定义切面

package com.example.test.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component; import java.lang.reflect.Method; @Component
@Aspect
public class MyAspect { //切入点,带有Myche注解并且是UserService类下的方法
@Pointcut("@annotation(com.example.test.aspect.MyCache)&&execution(* com.example.test.service.UserService.*(..))")
public void pointCut(){}; @Around("pointCut()")
public Object cache(ProceedingJoinPoint joinPoint)throws Throwable{
//获取方法签名
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
//获取目标方法
Method method = methodSignature.getMethod();
// Method method2 = joinPoint.getTarget().getClass().getMethod(methodSignature.getName(),methodSignature.getParameterTypes());
//获取方法上的注解
MyCache myCache = method.getDeclaredAnnotation(MyCache.class);
//得到el表达式
String el = myCache.value();
//解析el表达式,将#id等替换为参数值
ExpressionParser expressionParser = new SpelExpressionParser();
Expression expression = expressionParser.parseExpression(el);
EvaluationContext context = new StandardEvaluationContext();
String[] parameterNames = methodSignature.getParameterNames();
Object[] args = joinPoint.getArgs();
for (int i = 0; i <parameterNames.length ; i++) {
context.setVariable(parameterNames[i],args[i]);
}
String key = expression.getValue(context).toString();
System.out.println(key);
//根据key从缓存中拿数据,这里省略 //如果缓存中没有则执行目标方法
Object o = joinPoint.proceed();
//将结果放入缓存,这里省略 return o; }
}

  测试的service

package com.example.test.service;

import com.example.test.aspect.MyCache;
import org.springframework.stereotype.Service; @Service
public class UserService implements UserServiceInterface{ @MyCache("'asd_' + #id")
@Override
public void addUser(String id,String name){
System.out.println(id + "----" + name);
}
}

  测试类,这里是springboot项目

package com.example.test;

import com.example.test.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@SpringBootTest
public class TestApplicationTests { @Autowired
private UserService userService; @Test
public void contextLoads() {
System.out.println(userService.getClass().getName()); userService.addUser("12345" ,"zhagnsan");
} }

  执行结果如下:

  修改UserService上的注解为:"'asd_' + #id + '_' + #name",结果如下

使用spring EL表达式+自定义切面封装缓存模块的更多相关文章

  1. Spring EL表达式和资源调用

    Spring EL表达式     Spring EL-Spring表达式语言,支持在xml和注解中使用表达式,类似于在jsp的EL表达式语言.     Spring 开发中经常涉及调用各种资源的情况, ...

  2. 把功能强大的Spring EL表达式应用在.net平台

    Spring EL 表达式是什么? Spring3中引入了Spring表达式语言—SpringEL,SpEL是一种强大,简洁的装配Bean的方式,他可以通过运行期间执行的表达式将值装配到我们的属性或构 ...

  3. EL表达式---自定义函数(转)

    EL表达式---自定义函数(转) 有看到一个有趣的应用了,转下来,呵呵!! 1.定义类MyFunction(注意:方法必须为 public static) package com.tgb.jstl;  ...

  4. Spring 在 xml配置文件 或 annotation 注解中 运用Spring EL表达式

    Spring  EL 一:在Spring xml 配置文件中运用   Spring EL Spring EL 采用 #{Sp Expression  Language} 即 #{spring表达式} ...

  5. EL表达式自定义函数

    表达式语言除了可以使用基本的运算符外,还可以使用自定义函数.通过使用自定义函数,加强了表达式语言的功能. EL表达式函数,主要功能是完成对数据的修改,统一化格式: 步骤 1.开发函数处理类,处理类就是 ...

  6. 解决spring el表达式不起作用

    el表达式不起作用,如下图所示 现象: 在显示页面中加入: <%@ page isELIgnored="false" %>就OK了 参考:http://bbs.csdn ...

  7. java MVEL2/Spring EL表达式、直接调用、反射性能实测

    import java.io.Serializable; import java.lang.reflect.Field; import java.util.HashMap; import java.u ...

  8. spring EL表达式,null-safe表达式

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://ww ...

  9. Spring整合Shiro并扩展使用EL表达式

    Shiro是一个轻量级的权限控制框架,应用非常广泛.本文的重点是介绍Spring整合Shiro,并通过扩展使用Spring的EL表达式,使@RequiresRoles等支持动态的参数.对Shiro的介 ...

随机推荐

  1. 基于beego orm 针对oracle定制

    目前golang的ORM对oracle支持都没有mysql那样完整,一个orm要同时兼容mysql和oracle由于在sql语法上区别,会使整orm变的非常臃肿. 本项目是在beego orm上修改, ...

  2. Java转换Json日期/Date(1487053489965+0800)/格式以及js时间格式 Tue Feb 14 2017 14:06:32 GMT+0800

    /Date(1487053489965+0800)/用Java怎么转换成yyyy-MM-dd的格式 Tue Feb 14 2017 14:06:32 GMT+0800用Java怎么转换成yyyy-MM ...

  3. Nginx中间件使用心得(三)

    一.Nginx搭建系统需求 1.系统硬件:CPU >= 2Core,内存 >= 256M      2.自行搭建服务器(Linux操作系统) (1) 使用vmWare虚拟服务器 (2)使用 ...

  4. /usr/include/boost/python/detail/wrap_python.hpp:50:23: fatal error: pyconfig.h: No such file or directory

    https://stackoverflow.com/questions/39111930/usr-include-boost-python-detail-wrap-python-hpp5023-fat ...

  5. (最小生成树)Truck History --POJ -- 1789

    链接: http://poj.org/problem?id=1789 Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 2213 ...

  6. Spark RDD详解

    1.RDD是什么 RDD(Resilient Distributed Dataset):是Spark的核心数据结构,指的是一个只读的.可分区的分布式数据集,这个数据集的全部或部分可以缓存在内存中,在多 ...

  7. readLine() 和 "\r","\n" 问题

    很多输入流中都有一个函数readLine(),我们也经常使用这个函数,但有时如果不认真考虑,这个函数也会带来一些小麻烦. 如果我们是从控制台读入的话,我们也许没有想过readLine函数到底是根据&q ...

  8. spring MVC controller中的方法跳转到另外controller中的某个method的方法

    1. 需求背景     需求:spring MVC框架controller间跳转,需重定向.有几种情况:不带参数跳转,带参数拼接url形式跳转,带参数不拼接参数跳转,页面也能显示. 本来以为挺简单的一 ...

  9. 【TypeScript】TypeScript 学习 3——类

    在 EcmaScript 6 中,我们将会拥有原生的类,而不是像现在通过原型链来实现.使用 TypeScript 我们能提前体验这一特性. 首先来看看一个简单的例子: class Greeter { ...

  10. 【Win10】开发中的新特性及原有的变更(二)

    声明:本文内容适用于 Visual Studio 2015 RC 及 Windows 10 10069 SDK 环境下,若以后有任何变更,请以新的特性为准. 十一.x:Bind 中使用强制转换 这点是 ...