Search code examples
javaspring-bootcxf

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


I have CXF Rest Api with using Spring Boot, so here's my 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

My endpoints are annotated as @Component, but the problem is I have not only the components or providers, but also ExceptionMappers, In/Out/Fault Interceptors.

Now I'm wondering if it can be configured via properties file as well.

And I know possible solution (don't propose me this one):

@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();
}

This is not cool at all as far as so many features can be configured automatically and now for some additional configs I have to configure everything manually.

It kills the purpose of using Spring Boot at all. So.. any suggestions?


Solution

  • Please check 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