使用Spring Boot的Java自定义注释

时间:2018-09-12 16:43:09

标签: java spring spring-boot design-patterns reflection

我正在构建一个可以访问客户端代码并找到与注释关联的值的SDK。 我有两个自定义注释:

@Constraint(validatedBy = CustomizationValidator.class)
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Customization {

String id();
String state();

}

AND

@Constraint(validatedBy = ActionValidator.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Action {
String id();
String[] customizationId();
}

客户端代码如下:

@Service
public class ClientService {

   @Customization(id = "test", state = "SomeState")
   public String method2(final String id) {
       return "Doing Something in method 2 " + id;
 }
}

@Slf4j
@Component
@Action(id = "TestAction", customizationId = "test")
public class ActionConfigImpl implements ActionConfiguration<String> {


    @Override
    public String getName() {
        return "ActionConfigImpl";
    }

    @Override
    public String execute(final Map map) {
        log.info("Map in Execute: {}", map);
        log.info("In Execute of ActionConfigImpl");
        return "Some";
    }


    @Override
    public void destroy() throws Exception {
        log.info("In destroy");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("In afterPropertiesSet");
    }
}

注释处理器具有类似于以下代码的内容,用于查找注释的值:

final Class<?> aClass = actionConfiguration.getClass();
final Action action = aClass.getAnnotation(Action.class);

如果actionConfiguration是上述类定义的ActionConfigImpl对象(由Spring创建),则上面的代码能够找到action的值。

但是如果我在与下面相同的类中具有@Action和@Customization的嵌套注释,则无法使用。

@Slf4j
@Component
@Action(id = "TestAction1", customizationId = "testCP1")
public class ActionConfigImpl implements ActionConfiguration<String> {


    @Override
    public String getName() {
        return "ActionConfigImpl";
    }

    @Override
    @Customization(id = "testCP2", state = "sampleState1")
    public String execute(final Map map) {
        log.info("Map in Execute: {}", map);
        log.info("In Execute of ActionConfigImpl");
        return "Some";
    }


    @Override
    public void destroy() throws Exception {
        log.info("In destroy");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("In afterPropertiesSet");
    }
}

对于以上代码

final Class<?> aClass = actionConfiguration.getClass();
final Action action = aClass.getAnnotation(Action.class);

action的值为null。

不知道为什么。有人可以帮忙吗?

0 个答案:

没有答案