其他分享
首页 > 其他分享> > Spring bean没有注入CXF Web服务,为什么?

Spring bean没有注入CXF Web服务,为什么?

作者:互联网

我正在编写一个RESTful服务(在JBoss上使用CXF),我在其中使用Spring(Autowired)注入另一个类.但是这个类没有被注入而且是空的.

Web服务接口和类(需要注入的地方)

package com.company.project.web;

@Path("/myws")
public interface IMyWebService {    
   @POST
   @Path("/doSomething")    
   @Consumes("application/json")
   @Produces("application/json")
    MyResponse doSomething(MyRequest myRequest)
}

@Service("myWebService")
public class MyWebService implements IMyWebService {    
    @Autowired
    private IMyCore myCore;

    public MyResponse doSomething(MyRequest myRequest) {
      ....
    }
}

那必须注入

package com.company.project.biz;

public interface IMyCore {
   MyResponse doSomething(MyRequest myRequest);
}

@Component("myCore")
public class MyCore implements IMyCore {
    public MyResponse doSomething(MyRequest myRequest) {
            .....
    }
}

beans.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:jaxrs="http://cxf.apache.org/jaxrs"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd    
    http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <import resource="classpath:META-INF/cxf/cxf.xml" />
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-http.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />

    <context:annotation-config />
    <context:component-scan base-package="com.company.project"/>    

    <jaxrs:server id="myWebService" address="/">
        <jaxrs:serviceBeans>
            <bean class="com.company.project.web.MyWebService" />
        </jaxrs:serviceBeans>
        <jaxrs:extensionMappings>
            <entry key="json" value="application/json" />
        </jaxrs:extensionMappings>
    </jaxrs:server>
</beans>

我的服务处于活动状态(http://localhost:8080/{warname}/myws/doSomething),但MyCore实例未被注入MyWebService(在myCore字段中).它始终为null,我的服务无法按预期工作,而是抛出NullPointerException

尝试通过谷歌收集的所有输入.没运气!非常感谢您的帮助.

问候

解决方法:

尝试将以下方法添加到您的Web服务:

@PostConstruct
public void init() {
    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}

当前的Web应用程序上下文(通常是ContextLoaderListener加载的上下文)将用于自动装配,因此IMyCore bean必须在上下文侦听器配置文件中定义,而不是在Web服务中定义.

标签:jboss6-x,spring,cxf
来源: https://codeday.me/bug/20191005/1857475.html