Gert Cuykens
Gert Cuykens

Reputation: 7155

Jersey 2: how to bind injection classes without package scanning?

Originally I did include my classes manually by doing this

@ApplicationPath("/")
public class RestApplication extends Application {
    @Override
    public Set<Class<?>> getClasses() {
        final Set<Class<?>> classes = new HashSet<Class<?>>();
        classes.add(RestServlet.class);
        classes.add(RestService.class);
        return classes;
    }
}

Then I found out in order to be able to inject RestService in RestServlet I need to use a ResourceConfig binder instead.

public class RestApplication extends ResourceConfig {
    public RestApplication() {
        register(new RestBinder());
        packages(true, "");
    }
}

But I can't figure out how to use ResourceConfig without defining a package and bind it manually for each injection class?

PS I also don't understand how to make sure all package scanning is disabled?

Upvotes: 1

Views: 2457

Answers (1)

Michal Gajdos
Michal Gajdos

Reputation: 10379

You can use ResourceConfig#register() method for this purpose as well:

public class RestApplication extends ResourceConfig {
    public RestApplication() {
        register(new RestBinder());

        register(RestServlet.class);
        register(RestService.class);
    }
}

With this kind of registration your packages are not scanned for any other additional resources or providers. Providers discoverable via META-INF/services are still registered into your application. You can turn this feature off via, for server and client, jersey.config.disableMetainfServicesLookup property or, for server only, jersey.config.disableMetainfServicesLookup.server (you can find this and other properties in ServerProperties class):

public class RestApplication extends ResourceConfig {
    public RestApplication() {
        register(new RestBinder());

        register(RestServlet.class);
        register(RestService.class);

        property(ServerProperties.METAINF_SERVICES_LOOKUP_DISABLE, true);
    }
}

Upvotes: 1

Related Questions