zoukankan      html  css  js  c++  java
  • 结合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;
            }
        }
    }
    

      

  • 相关阅读:
    Matlab中将数据保存为txt或dat格式四种方案
    jeecg项目能启动显示登录页面,但是登录失败,报如下错误
    回转体CAD模型的厚度测量
    安装 PostgreSQL 时出错:Warning:Problem running post-install step
    TensorFlow 张量变换
    RNNCell、LSTMCell、tf.nn.static_rnn、tf.nn.static_bidirectional_rnn和tf.nn.bidirectional_dynamic_rnn
    layers.MaxPooling1D
    tf.squeeze
    tf.layers.Conv1D,1维卷积层
    tf.keras.layers.TimeDistributed,将一个layer应用到sample的每个时序步
  • 原文地址:https://www.cnblogs.com/ph123/p/5631030.html
Copyright © 2011-2022 走看看