Jacob van Lingen Jacob van Lingen - 2 months ago 13
Java Question

Dynamic applicationpath

A new application of ours uses multi-tenancy with multiple database. By providing a tenant id in the URL, we can select the right datasource.

But by using that kind of method, the namespace of the URL becomes dynamic (e.g.: instead of

/api
the url changes to
/{id}/api
). So is it possible to use a dynamic @ApplicationPath?

Just as it is possible to use a variable in the @Path annotation, could I write something like
@ApplicationPath("/tenants/{id}/api")
?

Answer

Seems applicationpath does not support dynamic segments. In the end we fixed it by using sub-resources:

Config

@ApplicationPath("tenants")
public class TenantConfig extends ResourceConfig {

    public TenantConfig(ObjectMapper mapper) {
        //set provider + add mapper

        register(TenantsController.class);
    }
}

TenantsController

@Path("/{id}/api")
public class TenantsController {

   //register all your controllers including path here

    @Path("/somethings")
    public Class<SomethingController> something() {
        return SomethingController.class;
    }
}

SomethingController

@Component
//Don't use @Path, as path info is already defined in the TenantsController
public class SomethingController {
    //do your stuff here;

    @GET
    @Path("/{id}") //Path for this example would be /tenants/{id}/api/somethings/{id}
    public JsonApiResult get(@PathParam("id") int id) {
       //retrieve one something
    }
}
Comments