栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Spring Boot将JAX-WS Web服务注册为Bean

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot将JAX-WS Web服务注册为Bean

SpringBeanAutowiringSupport
推荐使用扩展方法,从当前的Spring根Web应用程序上下文中为JAX-
WS端点类注入bean。但是,这不适用于 spring boot,
因为它在servlet上下文初始化方面有些不同。

问题

SpringBootServletInitializer.startup()
使用自定义
ContextLoaderListener
,并且不会将创建的应用程序上下文传递给
ContextLoader
。稍后,当初始化JAX-
WS端点类的对象时,
SpringBeanAutowiringSupport
依赖于
ContextLoader
检索当前应用程序上下文,并始终获取
null

public abstract class SpringBootServletInitializer implements WebApplicationInitializer {    @Override    public void onStartup(ServletContext servletContext) throws ServletException {        WebApplicationContext rootAppContext = createRootApplicationContext(     servletContext);        if (rootAppContext != null) { servletContext.addListener(new ContextLoaderListener(rootAppContext) {     @Override     public void contextInitialized(ServletContextEvent event) {         // no-op because the application context is already initialized     } });        }        ......    }}

解决方法

您可以注册一个实现

org.springframework.boot.context.embedded.ServletContextInitializer
了在期间检索应用程序上下文的bean
startup()

@Configurationpublic class WebApplicationContextLocator implements ServletContextInitializer {    private static WebApplicationContext webApplicationContext;    public static WebApplicationContext getCurrentWebApplicationContext() {        return webApplicationContext;    }    @Override    public void onStartup(ServletContext servletContext) throws ServletException {        webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);    }}

然后,您可以在JAX-WS端点类中实现自动装配。

@WebServicepublic class ServiceImpl implements ServicePortType {    @Autowired    private FooBean bean;    public ServiceImpl() {        AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();        WebApplicationContext currentContext = WebApplicationContextLocator.getCurrentWebApplicationContext();        bpp.setBeanFactory(currentContext.getAutowireCapableBeanFactory());        bpp.processInjection(this);    }    // alternative constructor to facilitate unit testing.    protected ServiceImpl(ApplicationContext context) {        AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();        bpp.setBeanFactory(new DefaultListableBeanFactory(context));        bpp.processInjection(this);    }}

单元测试

在单元测试中,您可以注入当前的spring应用程序上下文,并使用它调用替代构造函数。

@Autowired private ApplicationContext context;private ServicePortType service;@Beforepublic void setup() {    this.service = new ServiceImpl(this.context);}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/509112.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号