Autodiscover JAX-RS resources with CXF in a Spring application

前端 未结 4 2079

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

提交回复
热议问题