注解类
import java.lang.annotation.*;
/**
* Created by Administrator on 2016/6/28.
*/
//ElementType.METHOD 在方法上使用
@Target(ElementType.METHOD)
//范围
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Cacheable {
String key();
String fieldKey() ;
int expireTime() default 1800000;
}
注解实现类
@Aspect
public class CacheAspect { private Logger logger = LoggerFactory.getLogger(CacheAspect.class); public CacheAspect(){ } @Pointcut(value = "execution(@Cacheable * *.*(..))") public void setCacheRedis(){} /** * aop实现自定缓存注解 * * @param joinPoint * @return */
//@Around("@annotation(com.manage.annotations.Cacheable)") 不知道为什么这么写不行
//这个里面的值要上面的方法名一致 @Around("setCacheRedis()") public Object setCache(ProceedingJoinPoint joinPoint) { Object result = null; Method method = getMethod(joinPoint);
//自定义注解类 Cacheable cacheable = method.getAnnotation(Cacheable.class);
//获取key值
String key = cacheable.key();
String fieldKey=cacheable.fieldKey();
//获取方法的返回类型,让缓存可以返回正确的类型 Class returnType=((MethodSignature)joinPoint.getSignature()).getReturnType();
下面就是根据业务来自行操作 return result; } public Method getMethod(ProceedingJoinPoint pjp) { //获取参数的类型 Object[] args = pjp.getArgs(); Class[] argTypes = new Class[pjp.getArgs().length]; for (int i = 0; i < args.length; i++) { argTypes[i] = args[i].getClass(); } Method method = null; try { method = pjp.getTarget().getClass().getMethod(pjp.getSignature().getName(), argTypes); } catch (NoSuchMethodException e) { logger.error("annotation no sucheMehtod", e); } catch (SecurityException e) { logger.error("annotation SecurityException", e); } return method; } }
调用类
@Service
@Transactional
public class UserServiceImpl extends BaseServiceImpl<User, Integer> implements UserService {
@Autowired
private UserDaoImpl userDaoImpl;
@Override
//key名字自定义 fieldKey可以看Spring EL表达式
@Cacheable(key = "getUser",fieldKey = "#user.getUserName()")
public User getUser(User user) {
List<User> users = userDaoImpl.getUser(user);
if (!users.isEmpty() && users.size() > 0) {
user=users.get(0);
return user;
} else {
return null;
}
}
}