结合spring 实现自定义注解

注解类

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;
        }
    }
}

  

转载于:https://www.cnblogs.com/ph123/p/5631030.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值