Apache CXF jax-rs with Spring Boot:如何自动配置拦截器

Apache CXF jax-rs with Spring Boot: how to configure interceptors automatically

我有 CXF Rest Api 使用 Spring 引导,所以这是我的 application.properties:

cxf.path=/
cxf.jaxrs.server.address=/api
cxf.jaxrs.component-scan=true
cxf.jaxrs.classes-scan-packages=org.apache.cxf.jaxrs.swagger,org.apache.cxf.metrics

我的端点被注释为 @Component,但问题是我不仅有组件或提供者,还有 ExceptionMappers,In/Out/Fault 拦截器。

现在我想知道它是否也可以通过属性文件进行配置。

而且我知道可能的解决方案(不要向我推荐这个):

@Bean
public Server rsServer() {
  final JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean();

  endpoint.setInInterceptors(Arrays.<Interceptor<? extends Message>>asList(
    interceptor1,
    interceptor2,
    interceptor3
  ));

  endpoint.setOutInterceptors(Arrays.<Interceptor<? extends Message>>asList(out1));
  endpoint.setOutFaultInterceptors(Arrays.<Interceptor<? extends Message>>asList(out1));

  endpoint.setProviders(Arrays.asList(
    provider1(),
    provider2()
  ));

  endpoint.setBus(bus);

  endpoint.setAddress("/api");

  endpoint.setServiceBeans(Arrays.asList(
    endpoint1,
    endpoint2,
    ...,
    endpointN
  ));

  endpoint.setFeatures(Arrays.asList(new Swagger2Feature()));
  return endpoint.create();
}

这一点都不酷,因为可以自动配置这么多功能,现在对于一些额外的配置,我必须手动配置所有内容。

它完全扼杀了使用 Spring Boot 的目的。那么..有什么建议吗?

请检查CxfAutoConfiguration.java and AbstractSpringComponentScanServer.java, you need not create server bean manually, AutoConfiguration does for you, you need to just set property cxf.jaxrs.component-scan=true, it will add all spring beans annotated @Path and @Provider to server instance. If you have custom interceptors make it bean by adding @Component and @Provider(//with type). For Swagger and Metrics generally I create bean using @Bean, please check the example here

@karthik-prasadkart 的回答是正确的。如果你需要更大的灵活性,你也可以把它放到 false:

cxf.jaxrs.component-scan=false

并制作一个扩展 org.apache.cxf.jaxrs.spring.SpringComponentScanServer@Configuration class(因为通常由 cxf.jaxrs.component-scan=true 导入)。在这里您可以覆盖方法并进行最后一分钟的特定更改,例如在 org.apache.cxf.jaxrs.spring.AbstractSpringConfigurationFactory#finalizeFactorySetup 方法中专门用于此。

@Configuration
public class CxfServerConfig extends SpringComponentScanServer {

    @Override
    protected void finalizeFactorySetup(JAXRSServerFactoryBean factory) {
        super.finalizeFactorySetup(factory);

        // Don't bypasses our exception mappers
        factory.getProperties(true).put("support.wae.spec.optimization", false);
    }
}