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

      

  • 相关阅读:
    [小技巧]记录PHP错误日志
    PHP __autoload函数(自动载入类文件)的使用方法
    php5.3以前的版本安装出现Fatal error: Call to undefined function mysql_connect()
    mysqlnoinstall5.1.62win32 安装
    [php]PHP错误处理
    哈希表1
    哈希表2
    WinSock編程的多線程式控制
    编码转换 unicode gbk big5
    Parameters转换为Variant数组
  • 原文地址:https://www.cnblogs.com/ph123/p/5631030.html
Copyright © 2011-2022 走看看