eclipse-ee4j / jersey

Eclipse Jersey Project - Read our Wiki:
https://github.com/eclipse-ee4j/jersey/wiki
Other
689 stars 350 forks source link

Jsonb still not injectable #5697

Open hantsy opened 1 month ago

hantsy commented 1 month ago

The example project: https://github.com/hantsy/jakartaee11-sandbox/tree/master/rest

I have created a @Provider described like this:

@Provider
public class JsonbContextResolver implements ContextResolver<Jsonb> {
    @Override
    public Jsonb getContext(Class<?> type) {
        JsonbConfig config = new JsonbConfig()
                .withPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE_WITH_UNDERSCORES)
                .withFormatting(true)
                .withNullValues(false);
        return JsonbBuilder.newBuilder().withConfig(config).build();
    }
}

As discussed in here, https://github.com/jakartaee/rest/issues/742, a Jsonb instance should be available in the context.

@Inject Jsonb jsonb;

I tried to inject Jsonb, failed.

jansupol commented 1 month ago

This cannot work as you show. Once the ContextResolver<Jsonb> is at hand, the Jsonb context is obtained based on the supplied (entity) type.

The Spec mandates the following works in every implementation:

@Context Providers providers;
ContextResolver<Jsonb> contextResolver = providers.getContextResolver(Jsonb.class, MediaType.APPLICATION_JSON_TYPE);
Jsonb jsonb = contextResolver.getContext(type);

See Section 10 for mandatory injectable types.

jansupol commented 1 month ago

More specifically, the spec requested the JSON-B Message Body provider to automatically utilize the user-provided ContextResolver<Jsonb> by the JSON-B implementation used by that provider. Using this unified way to obtain the ContextResolver<Jsonb>. The customer needs just to register the ContextResolver without the need of taking care of the propagation of the Jsonb to the JSON-B implementation.

hantsy commented 1 month ago

The customer needs just to register the ContextResolver without the need of taking care of the propagation of the Jsonb to the JSON-B implementation.

Here I want to use jsonb bean to do some manual serialization work.

hantsy commented 1 month ago

When REST embraces CDI, I hope there is a united way to register beans via ContextResolver and CDI context.

  1. As I expected, when registering via Context resolver, provides beans in CDI context, or
  2. Using CDI @Produces to create the ConextResolver<Jsonb>, make jsonb available in Rest context and CDI context.

BTW, more easily for developers, as some frameworks provide, I would like to register a bean to customize JsonbConfig, then the REST CDI integration module will register ContextResolver<Jsonb> and produce Jsonb.

jansupol commented 1 month ago

I think the plan was to remove ContextResolver from Jakarta REST with CDI. But I am not sure what the replacement was. That is yet to be discussed.

jansupol commented 1 month ago

Maybe not, it is still there.