简体   繁体   中英

Check the arguments for all annotated methods at runtime

How can you perform a check at startup-time on all the usages of an annotation?

For instance, I have this aspect, that is applied to the methods annotated with @Protect , that applies some security policy. Across the system, we have methods annotated with @Protect("valid-operation-1") , @Protect("valid-operation-2") or @Protect("INVALID-operation") . As soon as the application starts up, I'd like to check the arguments provided for all these annotations in order to detect such misconfigurations.

In particular, I'll check that we have a bean defined in the Spring application context whose ID matches the argument of the annotation. That means, to protect the method void drive() , I'll annotate with @Protect("drive") , and expect a bean protect_drive to be present in the application context.

You can easily just wait until the method is invoked, then the advice is called, and you check the argument. Then you'll see that INVALID-operation is wrongly defined. But this is too late .

Is it possible to have this checked for all annotated methods when the application starts?

If the Classes you want to check are Spring Beans, then you can use a BeanPostProcessor .

public class OnlyAScratchForAnPostProcessor {

    @Inject
    private ApplicationContext context;


    @Override
    public Object postProcessAfterInitialization(final Object bean,
        final String beanName) throws BeansException {

          ReflectionUtils.doWithMethods(bean.getClass(), new MethodCallback() {

             @Override
             public void doWith(Method method) throws IllegalArgumentException,
                         IllegalAccessException {

                  String expecedNameFromAnnotation = scanAnnotation(method);
                  if(expecedNameFromAnnotation != null) {
                      if(context.beanByName(expecedNameFromAnnotation) != null) {
                         throw new RuntimeException("illegal configuration");
                      }
                  }         
             }

             String scanAnnotation(Method method){...}

          }, ReflectionUtils.USER_DECLARED_METHODS);        

    } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM