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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM