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