配置WebService前需要以下依赖jar包
#版本只供参考,具体看项目
编写配置类
import javax.xml.ws.Endpoint;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.http.MediaType;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBassedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.DispatcherServlet;
@Configuration
public class CxfConfig{
//配置WebService的前缀路径
@Bean
public ServletRegistrationBean dispatcherServlet(){
return new ServletRegistrationBean(new CXFServlet(), "/path/\*");
}
@Bean
public SpringBus springBus(){ return new SpringBus(); }
//实例化@webservice接口的实现类
@Bean
public \*\*\*\*Impl \*\*\*\*\*Impl(){ return new \*\*\*\*\*\*Impl(); }
//配置接口暴露路径(后缀路径)
@Bean
public Endpoint endpoint(){
EndpointImpl endpoint = new EndpointImpl(springBus(), \*\*\*\*\*Impl());
endpoint.publish("/Impl");
return endpoint;
}
}
问题一:配置webService后,Controller不能访问,失效
解决方法:
//controller失效,需要配置新的DispatcherServlet来扫描Controller的类
@Bean
public ServletRegistrationBean restServlet(){
//注解扫描上下文
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
//扫描Controller所在的路径
applicationContext.scan("com.brinfo.java.controller");
//通过构建函数指定dispatcherServlet的上下文
DispatcherServlet rest\_dispatcherServlet = new DispatcherServlet(applicationContext);
//用SetvletRegistrationBean包装servlet
ServletRegistrationBean registrationBean = new ServletRegistrationBean(rast\_dispatcherServlet);
//优先级
registrationBean.setLoadOnStartup(1);
//指定urlmapping
registrationBean.addUrlMappings("/\*");
return registrationBean;
}
问题二:前端跨域问题,需要后端配置跨域
private CorsConfiguration corsConfiguration(){
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("\*");
corsConfiguration.addAllowedHeader("\*");
corsConfiguration.addAllowedMethod("\*");
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setMaxAge(360011);
return corsConfiguration;
}
//解决跨域问题
@Bean
public CorsFilter corsFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/\*\*",corsConfiguration());
return new CorsFilter(source);
}
问题三:webService启动报错:Factory method 'endpoint' threw exception; nested exception is javax.xml.WebServiceException:org.apache.cxf.service.factory.ServiceConstructionException
记住!这个报错的原因之一 webService的入参和返回值可以void、String、不要写对象!
手机扫一扫
移动阅读更方便
你可能感兴趣的文章