Web服务中的Spring自动装配在测试时无法正常工作

时间:2014-09-01 23:01:08

标签: java spring web-services

我尝试配置这样的网络服务客户端:

@EnableSwagger
@Configuration
@EnableAutoConfiguration
@ComponentScan
@EnableWebMvc
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

使用WS的第二个配置类:

@Configuration
@ComponentScan(basePackages = {"org.myco.myproj.core.endpoints"})
public class WebServiceConfig {

    @Bean
    public Jaxb2Marshaller marshaller() throws Exception {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setContextPath("org.myco.myproj.core.webservices");
        return marshaller;
    }

    @Bean
    public WebServiceTemplate webServiceTemplate(Jaxb2Marshaller marshaller) {
        WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
        webServiceTemplate.setMarshaller(marshaller);
        webServiceTemplate.setUnmarshaller(marshaller);
        webServiceTemplate.setDefaultUri("http://localhost:11000/ws/");
        return webServiceTemplate;
    }

    @Bean
    public AccountEndpoint accountEndpoint(Jaxb2Marshaller marshaller, WebServiceTemplate webServiceTemplate) {
        AccountEndpoint client = new AccountEndpoint(webServiceTemplate);
        client.setDefaultUri("http://localhost:11000/ws");
        client.setMarshaller(marshaller);
        client.setUnmarshaller(marshaller);
        return client;
    }
}

我使用JABX从WSDL生成域类,并创建了这样的服务端点:

@Service
public class AccountEndpoint extends WebServiceGatewaySupport {

    private static final Logger logger = Logger.getLogger(String.valueOf(AccountEndpoint.class));

    private WebServiceTemplate webServiceTemplate;

    public AccountEndpoint(WebServiceTemplate webServiceTemplate) {
        this.webServiceTemplate = webServiceTemplate;
    }

    public GetAccountResponse getAccount(long accountAgency, long accountNumber) {
        GetAccountRequest request = new GetAccountRequest();
        request.setAccountAgency(accountAgency);
        request.setAccountNumber(accountNumber);

        GetAccountResponse response = (GetAccountResponse)
                webServiceTemplate.marshalSendAndReceive(request);

        return response;
    }
}

我创建了一个简单的测试来检查它是否正在运行,它在自动装配的字段中返回NullPointerException

 @ContextConfiguration("org.myco.myproj.config.WebServiceConfig")
    public class AccountEndpointTest extends TestCase {

        @Autowired
        private AccountEndpoint accountEndpoint;

        public void setUp() throws Exception {
            super.setUp();
        }

        @Test
        public void testGetAccount() throws Exception {

            GetAccountResponse response = accountEndpoint.getAccount(12, 16);

            assertNotNull(response);
        }
    }

我失踪了什么?感谢。

2 个答案:

答案 0 :(得分:2)

似乎你错过了

@RunWith(SpringJUnit4ClassRunner.class)

来自您的测试课程。否则,您正在使用默认的JUnit测试运行器,并且不涉及Spring。

答案 1 :(得分:-1)

不要声明变量WebServiceTemplate。请改用继承自WebServiceGatewaySupport的getWebServiceTemplate()。