users@jersey.java.net

[Jersey] How to Initialize Jersey Application (ResourceConfig) With Spring?

From: Michael Iles <michael.iles_at_gmail.com>
Date: Wed, 8 Jan 2014 09:59:08 -0500

(Cross-posted to SO:
http://stackoverflow.com/questions/20998983/how-to-initialize-jersey-application-resourceconfig-with-spring)

I'm using Jersey 2 and Spring, and I'm trying to initialize my Jersey
application (i.e. the class derived from ResourceConfig) with
parameters from the Spring context.

Background: I have a single Jersey application that I build (i.e. a
single WAR) and I deploy it across a server cluster with different
Spring configurations on different servers to enable or disable
different parts of the server, e.g. some of the servers have /search
resources turned on, etc. This was really easy in Jersey 1.0: I just
put,

<context:component-scan base-package="com.mycompany.resources.search"/>

in a Spring config to have Jersey scan that particular package and
enable the JAX-RS resource providers in it.

Now in Jersey 2.0 the Spring <context:component-scan ... /> doesn't
work, so resources have to be programmatically registered in a startup
class derived from ResourceConfig:

public class MyApplication extends ResourceConfig {

    public MyApplication() {
        packages("com.mycompany.resources.search");
    }
}

So far so good, but I need to conditionally scan that package, and I
can't figure out how to get any Spring configuration into the
MyApplication class. I thought that constructor injection might work:

public class MyApplication extends ResourceConfig {

    @Autowired
    public MyApplication(@Qualifier("my-config") MyConfiguration
myConfiguration) {
        if (myConfiguration.isEnabled()) {
            packages("com.mycompany.resources.search");
        }
    }
}

However HK2 complains that it can't find a default constructor to
use... so this indicates to me that DI is in play in the construction
of this class, but that the DI isn't using Spring.

Similarly, using the the Spring bean lifecycle doesn't work:

public class MyApplication extends ResourceConfig implements InitializingBean {

    @Autowired
    private MyConfiguration myConfiguration;

    public MyApplication() {
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (myConfiguration.isEnabled()) {
            packages("com.mycompany.resources.search");
        }
    }
}

(The afterPropertiesSet method isn't called.)

So now I'm stuck: is there any way to configuration a Jersey
ResourceConfig application object using Spring?


Thanks,
Mike.