使用 Jersey 1.x 进行自定义注释注入

2023-12-22

我使用的是球衣 1.9.1。我有如下休息方法 授权标头包含编码凭据,例如用户名 和密码,并在方法中解析并映射本地值。

@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];       
    }

我正在尝试设计一种方法来自动执行此过程,而无需在每个方法中编写相同的解析代码。我的意思是我想知道是否编写特殊注释,例如HeaderParamExtendedto this 用于解析此凭证。
我使用 jersey 1.9.1 版本作为rest api。我必须在该生命周期中的哪里编辑类?

@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 https://jersey.java.net/apidocs/1.7/jersey/com/sun/jersey/spi/inject/InjectableProvider.html支持自定义注入,还有Injectable https://jersey.java.net/apidocs/1.7/jersey/com/sun/jersey/spi/inject/Injectable.html提供价值。

这是一个例子

@BasicAuth

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface BasicAuth {
}

InjectableProvider

@Provider
public class BasicAuthInjectionProvider
        implements InjectableProvider<BasicAuth, Parameter> {

    @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<User>{

    @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 and password,并且只有一个注入点。 IE。

public Response getSomething(@BasicAuth User user) {
}

我实际上尝试按照你的方式做,

public Response getSomething(@BasicAuth("username") String username,
                             @BasicAuth("password") String password) {

并且在InjectableProvider从传递给的注释中获取注释值getInjectable,然后将该值传递给BasicAuthInjectable。从那里检查该值是否为"username" or "password"并返回相应的值。但由于某种原因,甚至没有打电话给注射提供者。您可以尝试一下它是否可以正常工作。但对我来说User无论如何看起来更干净,并且使用两个字符串,注入提供程序被调用两次,并且您需要解析标头两次。看来没有必要。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Jersey 1.x 进行自定义注释注入 的相关文章

随机推荐