Reputation: 707
When I have a very basic Application
, Jersey auto discovers all the REST resources in the project and I don't have to manually register them:
import javax.ws.rs.ApplicationPath;
@ApplicationPath("/rest")
public class Application extends javax.ws.rs.core.Application {
}
But when I switch to using the Jersey specific ResourceConfig
, auto discovery doesn't seem to work. I have to either #registerClasses()
or add the package as shown below:
@ApplicationPath("rest")
public class ResourceConfig extends org.glassfish.jersey.server.ResourceConfig {
public ResourceConfig() {
super();
register(RolesAllowedDynamicFeature.class);
super.packages(true, "org.example");
}
}
Is there a way to get ResourceConfig
to auto discover the REST resources like Application
without having to register the classes individually or having to add the application's package?
Upvotes: 4
Views: 4926
Reputation: 209122
Here's the deal: What causes classpath scanning, is an Application
class that does not register anything. So in your ResourceConfig
(which extends Application
), if you didn't register the RolesAllowedDynamicFeature
, you'd get the classpath scan. My guess is that you switched to the ResourceConfig
so that you could register the RolesAllowedDyanamicFeature
(maybe from some example you saw). This could also be done in the Application
class by overriding the getClasses()
. But like I said, once you register anything you lose the classpath scan, and you need to register everything manually.
One work around is to implement a Feature
to register all your classes that won't otherwise be picked up by the classpath scan.
@Provider
public class ClassPathScanWorkAroundFeature implements Feature {
@Override
public boolean configure(FeatureContext context) {
context.register(RolesAllowedDynamicFeauture.class);
return true;
}
}
This will work for both the Application
or the ResourceConfig
class. What happens during the classpath scan, is that Jersey will look for both @Path
and @Provider
annotated classes to register. So this is find of a workaround to register things manually and still maintain the classpath scan.
One thing I would point out, is the following article by one of Jersey's developers.
Basically they suggest never to use it. Personally I would just stick to the package scan. I don't think it really makes life that much more difficult. It's actually less code, than the alternative of using the Feature
.
Upvotes: 6