mardi 21 juin 2016

Creating a reusable "base" class extending javax.ws.rs.core.Application

The following is a question being implemented with Java EE 6 using the Java 7 JDK.

Situation

I'm trying to implement a solution where I have a sort of "core" or "base" version of a javax.ws.rs.core.Application class. I have a core framework that is a separate Java Project which at this point exists as a core.jar that other applications can include. What I want to do is have something like a "CoreApplication" in this core framework that extends the jax-rs Application class, which would look something like this:

@ApplicationPath("")
public class CoreApplication extends Application {

    @Override
    public Set<Class<?>> getClasses() {

        Set<Class<?>> resources = new HashSet<Class<?>>();

        resources.add(ApiListingResource.class);
        resources.add(SwaggerSerializers.class);
        // Other common resources from the core framework

        return resources;
    }

    @Override
    public Set<Object> getSingletons() {

        Set<Object> singletons = new HashSet<Object>();

        // Register the Jackson provider for JSON
        JacksonJaxbJsonProvider jaxbProvider = new JacksonJaxbJsonProvider();
        jaxbProvider.setMapper(getUniversalJacksonMapper());

        singletons.add(jaxbProvider);
        // Other common singletons from the core framework

        return singletons;
    } 
}

Problem

If I include my core.jar in an application that it is using and try to do something like this:

public class ChildApplication extends CoreApplication {

    @Override
    public Set<Class<?>> getClasses() {

        Set<Class<?>> resources = super.getClasses();

        resources.add(ChildSpecificResource.class);

        return resources;
    }

    ...

}

then this ChildApplication class is never run. What happens instead is that the CoreApplication class is run (assumedly because it actually extends the jax-rs Application class) and the ChildApplication is disregarded.

What I seem to need to do is make sure the ChildApplication class directly extends Application - that is apparently the only way it will be invoked. So if I do that then I need a way to inherit the CoreApplication class in my child applications. I thought of a couple of ways to try to solve this problem but neither work.

  1. Keep CoreApplication as a class and inherit both CoreApplication and Application from ChildApplication. This blatantly won't work because Java doesn't allow multiple inheritance.
  2. Make CoreApplication an interface. This would work in some regards but then I can only inherit the method signatures in ChildApplication which doesn't give me the real code reuse I'm after.

I was wondering if anyone could suggest the best design to solve this problem.

Thanks to all who help!

Aucun commentaire:

Enregistrer un commentaire