按包名扫描resteasy资源

时间:2015-07-24 15:10:46

标签: java rest configuration resteasy web.xml

我正在配置我的resteasy应用程序并需要启用自动扫描(两个jaxrs应用程序在类路径中并且在加载时中断)

因此我将web.xml配置如下:

    <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>

是否有任何方法可以通过包(com.mycompany.resource.*)名称进行扫描而不必添加每个资源?似乎有可能使用jaxrs而不是resteasy

2 个答案:

答案 0 :(得分:2)

文档很清楚:

  

要注册的完全限定的JAX-RS资源类名称的逗号分隔列表

您可以使用reflections库自行实现此功能。假设有以下文本文件:

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

我们可以在Application类中读取这个文本文件,搜索所有类并将其添加到getClasses返回的Set中:

@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;
    }

}

注意:我们只在类级添加@Path注释的资源。

答案 1 :(得分:0)

我不是jaxrs的专家,但你检查过下面的那些吗?

resteasy.scan 
resteasy.scan.resources 
相关问题