Search code examples
javarestconfigurationresteasyweb.xml

scan resteasy resources by package name


I'm configuring my resteasy app and need to turn of auto scanning (two jaxrs applications are in the classpath and it breaks at loading)

For that reason I have configured my web.xml as follow:

    <context-param>
    <param-name>resteasy.scan</param-name>
    <param-value>false</param-value>
</context-param>

<context-param>
    <param-name>resteasy.resources</param-name>
    <param-value>
        io.swagger.jaxrs.listing.ApiListingResource,
        com.mycompany.resource.ClientResource,
        com.mycompany.resource.AccountResource,
        ... etc
    </param-value>
</context-param>

Is there any way in resteasy to scan by package (com.mycompany.resource.*) name instead of having to add each resource ? It seems it's possible with jaxrs but not resteasy


Solution

  • The documentation is quite clear:

    A comma delimited list of fully qualified JAX-RS resource class names you want to register

    You could implement this on your own using for instance the reflections library. Assuming following textfile:

    com.foo.bar.TestResource
    com.foo.baz.*
    

    We can read this textfile in the Application class, search for all classes and add it to the Set returned by getClasses:

    @ApplicationPath("/")
    public class RestApplication extends Application {
    
        Set<Class<?>> classes;
    
        public RestApplication(@Context ServletContext servletContext) {
            classes = new HashSet<>();
            try {
                URI resourcesConfig = servletContext.getResource("/WEB-INF/resources.txt").toURI();
                List<String> resources = Files.readAllLines(Paths.get(resourcesConfig), Charset.forName("UTF-8"));
                for (String resource : resources) {
                    parseResources(resource);
                }
            } catch (IOException | URISyntaxException | ClassNotFoundException ex) {
                throw new IllegalArgumentException("Could not add resource classes", ex);
            }
        }
    
        private void parseResources(String resource) throws ClassNotFoundException, IOException {
            if (!resource.endsWith(".*")) {
                classes.add(Class.forName(resource));
                return;
            }
            String pkg = resource.substring(0, resource.length() - 2);
            Reflections reflections = new Reflections(pkg);
            for (Class<?> scannedResource : reflections.getTypesAnnotatedWith(Path.class)) {
                classes.add(scannedResource);
            }
        }
    
        @Override
        public Set<Class<?>> getClasses() {
            return classes;
        }
    
    }
    

    NOTE: We're only adding resources with a @Path annotation on the class level.