java自定义参数注解@Target(ElementType.PARAMETER)无效?

我自定义了一个参数注解@NotBlank, Target为(ElementType.PARAMETER) .

注解到方法的入参上, Aspect处理.

但是运行时,发现注解没生效,没进Aspect代码断点. 请大侠指点下.

代码如下:

  • 注解定义

package com.xxx.common.util;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * FileName: NotBlank
 * Description:
 * Version: v1.0.0
 * Author: liutf
 * Date: 2017-02-08
 */

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface NotBlank {

    String value() default "";

}
  • 注解使用

package com.xxx.service.impl;
import com.xxx.common.util.NotBlank;
import com.xxx.dao.ProductDefDAO;
import com.xxx.entity.ProductDefEntity;
import com.xxx.service.ProductDefService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import static com.xxx.common.constant.RigConst.DATA_STATE.VALID;

  @Service
  @Transactional
  @Slf4j
  public class ProductDefServiceImpl implements ProductDefService{
   @Autowired
   private ProductDefDAO dao;
   @Override
   @Cacheable(value="exProdCache")
   public ProductDefEntity getProduct(@NotBlank String channel) {
       ProductDefEntity entity = dao.findByChannelAndState(channel, VALID);
       if (entity == null) {
           log.error("渠道产品为空:channel:{}",channel);
       }
       return entity;
   }
  }
  • 注解Aspect处理


package com.xxx.common.util;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * FileName: NotBlankAspectHandler
 * Description:
 * Version: v1.0.0
 * Author: liutf
 * Date: 2017-02-08
 */

@Component
@Aspect
public class NotBlankAspectHandler {

    @Around("@annotation(NotBlank)")
    public Object validateAround(ProceedingJoinPoint joinPoint) throws Throwable {
        boolean result = false;
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();    //得到拦截的方法
        Object[] args = joinPoint.getArgs();        //方法的参数

        for (Object arg : args) {
            if (arg instanceof  String){
                Precondition.checkStringArgument((String) arg);
            }
        }

        System.out.println("校验完成..");

        return joinPoint.proceed();
    }


}
阅读 15.6k
2 个回答

没记错的话 @annotation表达式只会找方法上的注解。你在方法上自定义一个注解试试?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题