scan resteasy resources by package name

喜欢而已 提交于 2019-12-08 11:22:52

问题


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


回答1:


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.




回答2:


I`m not expert in jaxrs , but have you checked those below ?

resteasy.scan 
resteasy.scan.resources 


来源:https://stackoverflow.com/questions/31614046/scan-resteasy-resources-by-package-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!