'Inject HttpServerRequest in service via Quarkus

I'm trying to inject HttpServerRequest in service, but it always be null.

@Slf4j
@ApplicationScoped
public class TokenService {
    
    @Context
    HttpServerRequest request;
    
    public SysUser getUser() {
        String authorization = request.getHeader("Authorization");
        log.info(authorization);
        
        // find user by token
        return null;
    }
}
@Inject
TokenService tokenService;

After that, I tried to use @Context HttpServletRequest request as a part of the method parameter in resource. It worked for me.

    @GET
    @Path("routes")
    public Result<Object> routes(@Context HttpServerRequest request) {
        tokenService.getUser(request);
        return null;
    }
    public SysUser getUser(HttpServerRequest request) {
        String authorization = request.getHeader("Authorization");
        log.info(authorization);
        
        // find user by token
        return null;
    }

But I still want to inject HttpServerRequest in service. Anybody got an idea?



Solution 1:[1]

HttpServerRequest and other objects injected with @Context can only be injected into JAX-RS classes (that is resources and providers).

These classes cannot be injected into regular CDI beans, so you need to pass them as method params after you've obtained them via injection into a JAX-RS Reource (or provider)

Solution 2:[2]

If you want to access the request in other application scoped beans you can use below code instead of injecting which won't work as pointed by @geoand.

HttpServerRequest request = ResteasyProviderFactory.getInstance().getContextData(HttpServerRequest.class);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 geoand
Solution 2 Ubercool