Gui*_*ido 13 java spring cxf jax-rs
Apache CXF(2.7.0)是否可以自动发现类路径中的JAX-RS资源?也就是说,带有注释的类@Path.
我在Spring应用程序中使用CXF,我必须使用以下XML手动声明资源,即使Spring已成功发现资源<context:component-scan ...>.
<jaxrs:server id="myService" address="/myService">
<jaxrs:serviceBeans>
<ref bean="myResource1" />
<ref bean="myResource2" />
<ref bean="myResource3" />
</jaxrs:serviceBeans>
</jaxrs:server>
Run Code Online (Sandbox Code Playgroud)
我想避免它(因为我可以使用其他JAX-RS实现,例如resteasy)因为在我的情况下它更难维护,并且它迫使我在Spring XML配置文件中声明我的bean依赖项.
在cxf 3.0.4中测试并使用.
<jaxrs:server address="/" basePackages="a.b.c"/>
Run Code Online (Sandbox Code Playgroud)
别忘了在web.xml中提到cxf-servlet
小智 8
这段代码可以解决问题:
@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();
}
}
Run Code Online (Sandbox Code Playgroud)
记得把CXFServlet放到你的web.xml中就可以了.
| 归档时间: |
|
| 查看次数: |
8500 次 |
| 最近记录: |