Spring @Autowired在@WebService类中不起作用,但在Junit测试类中起作用

时间:2018-12-30 20:59:38

标签: java web-services spring-boot spring-bean spring-config

[EDIT]:我使用this post

的第二个解决方案解决了我的问题

我创建了一个WebApplicationContextLocator类:

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

然后我如下修改了SearchBookWebServiceImpl:

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import org.thibaut.thelibrary.webservice.configuration.WebApplicationContextLocator;

import javax.annotation.PostConstruct;
import javax.jws.WebMethod;
import javax.jws.WebService;


@Service
@Slf4j
@WebService(serviceName = "SearchBookService", portName = "SearchBookPort",
        targetNamespace = "http://thelibrary.service.ws/",
        endpointInterface = "org.thibaut.thelibrary.webservice.webservice.SearchBookWebService")
public class SearchBookWebServiceImpl extends AbstractWebService implements SearchBookWebService{

    @Override
    @WebMethod
    public String getBookTitle( Integer id ){
        return getServiceFactory().getBookService().getBookTitle( id );
    }

    public SearchBookWebServiceImpl() {
        AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
        WebApplicationContext currentContext = WebApplicationContextLocator.getCurrentWebApplicationContext();
        bpp.setBeanFactory(currentContext.getAutowireCapableBeanFactory());
        bpp.processInjection(this);
    }

    // alternative constructor to facilitate unit testing.
    protected SearchBookWebServiceImpl( ApplicationContext context) {
        AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
        bpp.setBeanFactory(new DefaultListableBeanFactory(context));
        bpp.processInjection(this);
    }

}

我只是不知道如何将我的问题标记为已回答,因为我无法标记任何答案...

我正在使用以下程序开发一个多模块应用程序:WebService,Springboot,Hibernate,Spring-data。我正在尝试使用自下而上的方法测试一个非常简单的Web服务(首先是类,然后自动生成wsdl文件)。

Spring注释@Autowired在我的小@WebService类中不起作用。因此,我无法从@WebService类访问@WebMethod中的spring bean。但是@Autowired在我用来测试@WebMethod的Junit测试类中可以正常工作。另外,WebService本身也是可访问的。我使用不需要任何bean的WebMethod进行了测试,并且可以正常工作。

[EDIT]:我刚刚发现了这篇文章Spring Boot register JAX-WS webservice as bean 我尝试了不同的解决方案,正确地理解了它们。但是,它解决了铅的问题。请参阅下面的我的Springboot应用程序(来自上面帖子的最后一个解决方案)。

我将此帖子设为红色:Why is my Spring @Autowired field null?。但这并不能影响我的铅含量。 (我没有使用“ new myObject()”代替Spring上下文,而且我的pb似乎更多地是关于“ javax.jws.WebService”注释类,而不是“ org.springframework.stereotype.Service”注释类) 我试图用XML声明我的bean,但是它没有任何改变。

我的@SpringbootApplication类:

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.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.thibaut.thelibrary.webservice.webservice.SearchBookWebService;
import org.thibaut.thelibrary.webservice.webservice.SearchBookWebServiceImpl;

import javax.xml.ws.Endpoint;

@SpringBootApplication
@ComponentScan(basePackages = {"org.thibaut.thelibrary"})
@EnableJpaRepositories(basePackages = {"org.thibaut.thelibrary"})
@EntityScan(basePackages = {"org.thibaut.thelibrary"})
public class Application {

    public static void main(String[] args) {

        SpringApplication.run( Application.class, args );

    }

    @Bean
    public ServletRegistrationBean dispatcherServlet() {
        return new ServletRegistrationBean(new CXFServlet(), "/soap-api/*");
    }

    @Bean(name = Bus.DEFAULT_BUS_ID)
    public SpringBus springBus() {
        return new SpringBus();
    }

    @Bean
    public SearchBookWebService searchBookWebService() {
        return new SearchBookWebServiceImpl();
    }

    @Bean
    public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(springBus(), searchBookWebService());
        endpoint.publish("/SearchBookWebService");
        return endpoint;
    }
}

我的@WebService实现类

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.jws.WebMethod;
import javax.jws.WebService;

@Service
@Slf4j
@WebService(serviceName = "SearchBookService", portName = "SearchBookPort",
targetNamespace = "http://thelibrary.service.ws/",
endpointInterface = "org.thibaut.thelibrary.webservice.webservice.SearchBookWebService")
public class SearchBookWebServiceImpl extends AbstractWebService implements     SearchBookWebService{

    @Override
    @WebMethod
    public String getBookTitle( Integer id ){
        return getServiceFactory().getBookService().getBookTitle( id );
    }

}

我的@WebService接口

import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService(targetNamespace = "http://thelibrary.service.ws/", name = "SearchBook")
public interface SearchBookWebService {

    @WebMethod
    abstract String getBookTitle( Integer id );

}

AbstractWebService类

@Service
public abstract class AbstractWebService {

    private ServiceFactory serviceFactory;

    ServiceFactory getServiceFactory( ) {
        return serviceFactory;
    }

    @Autowired
    public void setServiceFactory( ServiceFactory serviceFactory ) {
        this.serviceFactory = serviceFactory;
    }
}

ServiceFactory实现类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thibaut.thelibrary.service.contract.BookService;
import org.thibaut.thelibrary.service.contract.ServiceFactory;

@Component
public class ServiceFactoryImpl implements ServiceFactory {

    private BookService bookService;    

    @Override
    public BookService getBookService( ) {
        return bookService;
    }

    @Override
    @Autowired
    public void setBookService( BookService bookService ) {
        this.bookService = bookService;
    }
}

ServiceFactory接口:

public interface ServiceFactory {

    BookService getBookService( );

    void setBookService( BookService bookService );
}

RepositoryFactoryImpl类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.thibaut.thelibrary.repository.contract.RepositoryFactory;

@Component
public class RepositoryFactoryImpl implements RepositoryFactory {

    private BookRepository bookRepository;

    @Override
    public BookRepository getBookRepository( ) {
        return bookRepository;
    }

    @Override
    @Autowired
    public void setBookRepository( BookRepository bookRepository ) {
        this.bookRepository = bookRepository;
    }
}

BookRepository界面:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.stereotype.Repository;
import org.thibaut.thelibrary.domain.entity.Book;

@Repository
public interface BookRepository extends JpaRepository< Book, Integer >, 
QuerydslPredicateExecutor<Book> {
}

webservice模块maven pom:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
    <artifactId>thelibrary-webservice</artifactId>
    <groupId>org.thibaut.thelibrary</groupId>
    <version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>webservice</artifactId>
<packaging>war</packaging>


<dependencies>
    <dependency>
        <groupId>org.thibaut.thelibrary</groupId>
        <artifactId>service</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web-services</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
    </dependency>
    <!--<dependency>-->
        <!--<groupId>com.sun.xml.ws</groupId>-->
        <!--<artifactId>jaxws-ri</artifactId>-->
    <!--</dependency>-->
    <dependency>
        <groupId>javax.xml</groupId>
        <artifactId>webservices-api</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <finalName>thelibrary-webservice</finalName>

    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <mainClass>org.thibaut.thelibrary.webservice.application.Application</mainClass>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-clean-plugin</artifactId>
            <version>3.1.0</version>
        </plugin>

        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <version>3.1.0</version>
        </plugin>

        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M3</version>
        </plugin>

        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.2.2</version>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-install-plugin</artifactId>
            <version>3.0.0-M1</version>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-deploy-plugin</artifactId>
            <version>3.0.0-M1</version>
        </plugin>
    </plugins>
</build>

root pom:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<packaging>pom</packaging>

<modules>
    <module>domain</module>
    <module>repository</module>
    <module>service</module>
    <module>webservice</module>
    <module>webservice-example-from-oc</module>
</modules>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<groupId>org.thibaut.thelibrary</groupId>
<artifactId>thelibrary-webservice</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>thelibrary-webservice</name>
<description>A web service to manage a library</description>

<properties>
    <!--<java.version>1.8</java.version>-->
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <start-class>org.thibaut.thelibrary.webservice.application.Application</start-class>
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.thibaut.thelibrary</groupId>
            <artifactId>domain</artifactId>
            <version>0.0.1-SNAPSHOT</version >
        </dependency>
        <dependency>
            <groupId>org.thibaut.thelibrary</groupId>
            <artifactId>repository</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.thibaut.thelibrary</groupId>
            <artifactId>service</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.thibaut.thelibrary</groupId>
            <artifactId>webservice</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
            <version>3.2.7</version>
        </dependency>
        <!--<dependency>-->
            <!--<groupId>com.sun.xml.ws</groupId>-->
            <!--<artifactId>jaxws-ri</artifactId>-->
            <!--<version>2.3.1</version>-->
        <!--</dependency>-->
        <dependency>
            <groupId>javax.xml</groupId>
            <artifactId>webservices-api</artifactId>
            <version>@metro.version@</version>
        </dependency>
    </dependencies>
</dependencyManagement>

当我在Glassfish5中部署WebService战争时,我尝试测试getBookTitle()Web方法时,我遇到了NullPointerException,因为在我的AbstractWebService类中,serviceFactory bean为Null(知道这要归功于调试模式)。 我使用网址测试了该方法 http://desktop-11dqe2u.local:8080/thelibrary-webservice/SearchBookService?Tester 并且也通过SoapUi。 结果是一样的。

错误是:

java.lang.NullPointerException
    at org.thibaut.thelibrary.webservice.webservice.SearchBookWebServiceImpl.getBookTitle(SearchBookWebServiceImpl.java:20)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.glassfish.webservices.InstanceResolverImpl$1.invoke(InstanceResolverImpl.java:144)
    at com.sun.xml.ws.server.InvokerTube$2.invoke(InvokerTube.java:149)
    at com.sun.xml.ws.server.sei.SEIInvokerTube.processRequest(SEIInvokerTube.java:88)
    at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136)
    at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050)
    at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019)
    at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877)
    at com.sun.xml.ws.api.pipe.helper.AbstractTubeImpl.process(AbstractTubeImpl.java:136)
    at org.glassfish.webservices.MonitoringPipe.process(MonitoringPipe.java:142)
    at com.sun.xml.ws.api.pipe.helper.PipeAdapter.processRequest(PipeAdapter.java:119)
    at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136)
    at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050)
    at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019)
    at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877)
    at com.sun.xml.ws.api.pipe.helper.AbstractTubeImpl.process(AbstractTubeImpl.java:136)
    at com.sun.enterprise.security.webservices.CommonServerSecurityPipe.processRequest(CommonServerSecurityPipe.java:209)
    at com.sun.enterprise.security.webservices.CommonServerSecurityPipe.process(CommonServerSecurityPipe.java:141)
    at com.sun.xml.ws.api.pipe.helper.PipeAdapter.processRequest(PipeAdapter.java:119)
    at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136)
    at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050)
    at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019)
    at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877)
    at com.sun.xml.ws.server.WSEndpointImpl$2.process(WSEndpointImpl.java:419)
    at com.sun.xml.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:868)
    at com.sun.xml.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:422)
    at com.sun.xml.ws.transport.http.servlet.ServletAdapter.handle(ServletAdapter.java:169)
    at org.glassfish.webservices.JAXWSServlet.doPost(JAXWSServlet.java:169)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:706)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:791)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1580)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:338)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:250)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:652)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:591)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:463)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:168)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:242)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:539)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:593)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
    at java.lang.Thread.run(Thread.java:748)
]]

如果需要,这是指向我的GitHub存储库的链接:https://github.com/thibaut54/TheLibrary-WebService/tree/feature/webservice

0 个答案:

没有答案