2016-12-16 200 views
0

假設我在Java EE的一個下面的代碼/ EJB/JAX-RS:的Java EE - 如何在方法與自定義註解注入方法參數

如何檢查定製@MyAnnotation註釋的存在並且在註解存在的情況下基於一些請求上下文參數填充CustomValue value方法參數?

注意:我已經在Spring中使用了這個代碼,使用了HandlerInterceptorAdapterHandlerMethodArgumentResolver。現在我需要在沒有Spring的情況下做同樣的事情。我已經發現ContainerRequestFilter,我用它來檢查註釋,但現在我正在注入方法參數。

回答

0

自定義方法參數注入處理與正常(即字段,構造函數)注入有點不同。有了澤西島,這需要執行ValueFactoryProvider。對於你的情況下,它會看起來像

public class MyAnnotationParamValueProvider implements ValueFactoryProvider { 

    @Inject 
    private ServiceLocator locator; 

    @Override 
    public Factory<?> getValueFactory(Parameter parameter) { 
     if (parameter.getAnnotation(MyAnnotation.class) != null 
       && parameter.getRawType() == CustomValue.class) { 
      final Factory<CustomValue> factory 
        = new AbstractContainerRequestValueFactory<CustomValue>() { 
       @Override 
       public CustomValue provide() { 
        final ContainerRequest request = getContainerRequest(); 
        final String value = request.getHeaderString("X-Value"); 
        return new CustomValue(value); 
       } 
      }; 
      locator.inject(factory); 
      return factory; 
     } 
     return null; 
    } 

    @Override 
    public PriorityType getPriority() { 
     return Priority.NORMAL; 
    } 
} 

然後,你需要用ResourceConfig

public class AppConfig extends ResourceConfig { 
    public AppConfig() { 
     register(new AbstractBinder() { 
       @Override 
       protected void configure() { 
        bind(MyAnnotationParamValueProvider.class) 
         .to(ValueFactoryProvider.class) 
         .in(Singleton.class); 
       } 
     }); 
    } 
} 

註冊它見this Gist

還看到一個完整的例子:

+0

謝謝你的回答! :)有沒有辦法做到這一點沒有ResourceConfig類,例如使用註釋?我必須與Swift一起工作的管理員讓我柔軟......:D –

+0

所以你使用的是web.xml(和包掃描)?如果是這樣,看看[這篇文章](http://stackoverflow.com/a/29275727/2587435) –

+0

不,沒有web.xml ...和沒有包掃描。但基於[這篇文章](http://blog.dejavu.sk/2013/11/19/registering-resources-and-providers-in-jersey-2/),我相信包掃描可以在代碼中配置以及 - 我會給它一個鏡頭。 :) 謝謝! –