Autodiscover JAX-RS resources with CXF in a Spring application Autodiscover JAX-RS resources with CXF in a Spring application spring spring

Autodiscover JAX-RS resources with CXF in a Spring application


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


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.


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