使用Jersey 1.x自定义注释注入
我正在使用jersey1.9.1。 我有rest方法,如下所示,Authorization标头包含编码凭据,如用户名和密码,并在方法中解析并映射本地值。
@PUT @Path(SystemConstants.REST_MESSAGE_SENDSMS) @Consumes(MediaType.APPLICATION_JSON) @Produces({MediaType.APPLICATION_JSON}) public Response sendSms(@HeaderParam("Authorization") String authorization, String param) { String[] credentials = ImosUtils.getUserCredentials(authorization); String username = credentials[0]; String password = credentials[1]; }
我试图设计一种自动生成此过程的方法,而无需在每个方法中编写相同的解析代码。 我的意思是我想知道是否编写了一个特殊的注释,如HeaderParamExtended
用于解析此凭据。
我使用泽西1.9.1版作为restapi。 我必须在那个生命周期中编辑一个类?
@PUT @Path(SystemConstants.REST_MESSAGE_SENDSMS) @Consumes(MediaType.APPLICATION_JSON) @Produces({MediaType.APPLICATION_JSON}) public Response sendSms(@HeaderParamExtended("Authorization","username") String username, @HeaderParamExtended("Authorization","password") String password, , String param) { }
通常,您需要一个InjectableProvider
来支持自定义注入,还需要一个Injectable
来提供值。
这是一个例子
@BasicAuth
@Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface BasicAuth { }
InjectableProvider
@Provider public class BasicAuthInjectionProvider implements InjectableProvider { @Override public ComponentScope getScope() { return ComponentScope.PerRequest; } @Override public Injectable getInjectable(ComponentContext cc, BasicAuth a, Parameter c) { return new BasicAuthInjectable(); } }
Injectable
public class BasicAuthInjectable extends AbstractHttpContextInjectable{ @Override public User getValue(HttpContext hc) { String authHeaderValue = hc.getRequest() .getHeaderValue(HttpHeaders.AUTHORIZATION); String[] credentials = ImosUtils.getUserCredentials(authHeaderValue); return new User(credentials[0], credentials[1]); } }
你会注意到的一件事是我有一个User
类。 这是包装username
和password
,只有一个注入点。 即
public Response getSomething(@BasicAuth User user) { }
我实际上是试着用自己的方式做到的
public Response getSomething(@BasicAuth("username") String username, @BasicAuth("password") String password) {
在InjectableProvider
,从传递给getInjectable
的注释中获取注释值,然后将该值传递给BasicAuthInjectable
。 从那里检查值是"username"
还是"password"
并返回相应的值。 但由于某些原因,注射供应商甚至没有被召唤。 你可以玩它,看看你是否可以让它工作。 但对我来说, User
看起来更干净,并且使用两个字符串,注入提供程序被调用两次,您需要解析标题两次。 似乎没必要。