java自定义注释,用于修改getter方法的返回值

时间:2015-08-05 06:27:57

标签: java spring-mvc annotations

我的spring mvc项目中有一些实体。假设我有三个实体A,B和C.A有B和C的实例:

public class A {
   ...
   public B b;
   public B getB(){
      return b;
   }
   public void setB(B b){
      this.b = b;
   }


   public C c;
   public C getC(){
      return b;
   }
   public void setC(C c){
      this.c = c;
   }
}

我想在获取实例后修改实例。例如,我想在调用getB()表单A时设置B的某个字段。我不想手动执行此操作。例如,我想为此做一个注释。像这样:

public class A {
   ...
   public B b;

   @MyCustomAnnotation
   public B getB(){
      return b;
   }
   public void setB(B b){
      this.b = b;
   }


   public C c;

    @MyCustomAnnotation
   public C getC(){
      return b;
   }
   public void setC(C c){
      this.c = c;
   }
}

我该怎么做?

1 个答案:

答案 0 :(得分:0)

为什么Spring MVC自定义注释?如果我理解正确,你想拥有自己的注释,你可以应用于某些方法并执行一些逻辑。

创建您自己的注释,如下所示

注释@Target = ElementType.METHOD如下 -

@Validation(validator = Validator.MYLOGIC)
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation{

    int value();

}

对您的验证进行枚举,如下所示

public enum Validator {

    SOMEOTHERVALIDATION() {
         // Some other validation here
    },
    MYLOGIC() {

        // Have your business logic here

    };
public abstract List<String> validate(Object value,
            Map<String, Object> params, String variable);
}

拥有ValidationFactory,使用反射,获取注释并调用特定的验证逻辑

public class ValidationFactory {

    public void validate(Object object) throws HealthcareValidationException {

        List<String> exceptions = validateObject(object);
        if (exceptions.size() != 0) {
            throw new HealthcareValidationException(exceptions);
        }
    }

    public List<String> validateObject(Object obj) {
        List<String> validationResult = new ArrayList<String>();
        for (Field field : obj.getClass().getDeclaredFields()) {
            try {
                validationResult.addAll(validateField(field, obj));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return validationResult;
    }

    protected static List<String> validateField(Field field, Object obj)
            throws IllegalAccessException, InvocationTargetException {

        Annotation[] annotations = field.getDeclaredAnnotations();
        for (Annotation annotation : annotations) {
            Validation validationMarker = annotation.annotationType()
                    .getAnnotation(Validation.class);
            if (validationMarker != null) {
                Validator[] validators = validationMarker.validator();

                for (Validator validator : validators) {

                    field.setAccessible(true);
                    String xmlFileld = field.getName();

                    validationExceptions.addAll(validator.validate(
                            field.get(obj), collectParams(annotation),
                            xmlFileld));
                }
            }
        }
        return validationExceptions;
    }
}

导航流的面向方面编程

现在您已准备好自定义注释。您可以在任何方法中使用此批注。接下来,您可以使用面向Spring Aspect的编程将流程导航到注释逻辑。

示例 - 假设您要与特定包中的所有方法或名称以insert *

开头的所有方法相交
@Before("execution(* com.learning.application.bo.*.insert*(..))")
    public void validateInsert(JoinPoint joinpoint)
            throws HealthcareValidationException {

        validationFactory = new ValidationFactory();
        Object[] args = joinpoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            validationFactory.validate(args[i]);
        }
    }

就是这样!希望这可以帮助。