使用Springboot将HeaderParam反序列化为POJO

时间:2017-08-23 20:01:31

标签: java spring spring-boot

作为我的其余API的一部分,我需要访问存储在Authorization标头中的运算符。

我可以像访问:

@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public Customer post(@RequestBody CustomerRequest request, @RequestHeader(name = "Authorization") String authorization) {
    // Some logic to parse the authorization header here which gets duplicated in every REST method
    Operator operator = parseAuthorization(authorization);
}

然而,这有点尴尬,并且在使用它时需要大量重复的代码。

有没有办法可以使用自定义注释和某种形式的中间件来实现这一点:

@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public Customer post(@RequestBody CustomerRequest request, @Operator Operator operator) {
}

3 个答案:

答案 0 :(得分:1)

这可以使用Spring Converters来完成,例如

@Component
public class OperatorHeaderConverter implements Converter<String, Operator> {

    private final AuthenticationService service;

    @Autowired
    public OperatorHeaderConverter(AuthenticationService service) {
        this.service = service;
    }

    @Override
    public Operator convert(String source) {
        return service.parseAuthorization(source);
    }
}

使用以下配置:

@Configuration
public class ControllerConfiguration extends WebMvcConfigurerAdapter {

    private final OperatorHeaderConverter operatorHeaderConverter;

    @Autowired
    public ControllerConfiguration(OperatorHeaderConverter converter) {
        this.operatorHeaderConverter = converter;
    }

    @Override
    public void addFormatters (FormatterRegistry registry) {
        registry.addConverter(operatorHeaderConverter);
    }

}

用于控制器,如:

@RequestMapping(method = RequestMethod.GET, produces = "application/json")
public List<CustomerResponse> getCustomers(@RequestHeader(name = "Authorization") Operator operator) {
    // Do something with the operator
}

答案 1 :(得分:0)

您可以在点击任何控制器之前使用过滤器或拦截器来读取身份验证标头。

答案 2 :(得分:0)

您可以将每个类用于头参数,但是您需要配置Spring,因此它可以将头值的String转换为该类。 最简单的方法是使用PropertyEditor。

实现一个类授权,为操作符添加一个字段(如果你愿意,可以添加getter)

public class Authorization{
  public Operator operator;
}

创建java.beans.PropertyEditorSupport的子类,将头String转换为授权

public class AuthorizationEditor extends PropertyEditorSupport {

@Override
public void setAsText(String text) throws IllegalArgumentException{
  //create the Authorization with the Operator here
  Authorization authorization = 
  setValue(authorization)
}

@Override
public String getAsText() {
  //does not matter, is unused here
  return null;
}
}

重要 将AuthorizationEditor类放在与Authorization相同的包中,Spring会自动在那里找到它。

使用授权作为标头参数的类型

public Customer post(... @RequestHeader(name = "Authorization") Authorization authorization)