Autodiscover JAX-RS resources with CXF in a Spring application

前端 未结 4 2078

Is it possible with Apache CXF (2.7.0) to automatically discover JAX-RS resources in the classpath? That is, classes annotated with @Path.

相关标签:
4条回答
  • 2020-12-09 11:31

    In addition to what has been suggested: it works indeed in 3.0.0-milestone2, one would just do a top level jaxrs server declaration only and set basePackages attribute which may have one or more space separated package names.

    0 讨论(0)
  • 2020-12-09 11:33

    This code does the trick:

    @Configuration
    @ComponentScan
    @ImportResource({"classpath:META-INF/cxf/cxf.xml"})
    public class Context {
        @Autowired
        private ApplicationContext ctx;
    
        @Bean
        public Server jaxRsServer() {
            LinkedList<ResourceProvider> resourceProviders = new LinkedList<>();
            for (String beanName : ctx.getBeanDefinitionNames()) {
                if (ctx.findAnnotationOnBean(beanName, Path.class) != null) {
                    SpringResourceFactory factory = new SpringResourceFactory(beanName);
                    factory.setApplicationContext(ctx);
                    resourceProviders.add(factory);
                }
            }
    
            JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();
            factory.setBus(ctx.getBean(SpringBus.class));
            factory.setProviders(Arrays.asList(new JacksonJsonProvider()));
            factory.setResourceProviders(resourceProviders);
            return factory.create();
        }
    }
    

    Just remember to put CXFServlet into your web.xml and you are done.

    0 讨论(0)
  • 2020-12-09 11:46

    Tested and working in cxf 3.0.4.

    <jaxrs:server address="/" basePackages="a.b.c"/>
    

    Dont forget to mention the cxf-servlet in web.xml

    0 讨论(0)
  • 2020-12-09 11:54

    It doesn't look like there's a way to do this with Spring configuration at this time in CXF 2.7. If you look at resteasy they've implemented a BeanFactoryPostProcessor SpringBeanProcessor.java that looks for @Path and @Provider. Something similar could be probably be done in CXF but it doesn't appear to be implemented yet. Looks like you're not the only one interested CXF-3725

    0 讨论(0)
提交回复
热议问题