您的位置:

Spring Boot实现Web Service接口调用

一、SOAP和RESTful协议

SOAP(Simple Object Access Protocol)和RESTful(Representational State Transfer)是两种常见的Web Service协议。SOAP是基于XML和HTTP协议的,是一种重量级协议;RESTful则是基于HTTP协议的,主要使用JSON数据格式,是一种轻量级协议。

在Spring Boot中,可以选择使用SOAP或RESTful协议进行Web Service接口调用。如果需要保证数据的安全性和事务一致性,SOAP是一个不错的选择;如果接口简单,数据格式较为简单,则可以选择RESTful协议。

二、SOAP协议下的Web Service接口调用

1、首先,在pom.xml中加入以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web-services</artifactId>
</dependency>

2、在Spring Boot主类中添加@EnableWs和@Bean注解,开启Web Service支持,并定义WebService接口:

@SpringBootApplication
@EnableWs
public class DemoApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(DemoApplication.class);
    }

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

    @Bean
    public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
        MessageDispatcherServlet servlet = new MessageDispatcherServlet();
        servlet.setApplicationContext(applicationContext);
        servlet.setTransformWsdlLocations(true);
        return new ServletRegistrationBean(servlet, "/ws/*");
    }

    @Bean(name = "countries")
    public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema countriesSchema) {
        DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
        wsdl11Definition.setPortTypeName("CountriesPort");
        wsdl11Definition.setLocationUri("/ws");
        wsdl11Definition.setTargetNamespace("http://spring.io/guides/gs-producing-web-service");
        wsdl11Definition.setSchema(countriesSchema);
        return wsdl11Definition;
    }

    @Bean
    public XsdSchema countriesSchema() {
        return new SimpleXsdSchema(new ClassPathResource("countries.xsd"));
    }

    @WebService
    public interface CountryService {
        @WebMethod
        String getCapital(String countryName);
        @WebMethod
        String getCurrency(String countryName);
    }

    @Service
    public class CountryServiceImpl implements CountryService {

        private Map<String, Country> countries = new HashMap<>();

        public CountryServiceImpl() {
            Country spain = new Country();
            spain.setName("Spain");
            spain.setCapital("Madrid");
            spain.setCurrency(Currency.EUR);
            countries.put(spain.getName(), spain);

            Country poland = new Country();
            poland.setName("Poland");
            poland.setCapital("Warsaw");
            poland.setCurrency(Currency.PLN);
            countries.put(poland.getName(), poland);

            Country uk = new Country();
            uk.setName("United Kingdom");
            uk.setCapital("London");
            uk.setCurrency(Currency.GBP);
            countries.put(uk.getName(), uk);
        }

        @Override
        public String getCapital(String countryName) {
            return countries.get(countryName).getCapital();
        }

        @Override
        public String getCurrency(String countryName) {
            return countries.get(countryName).getCurrency().toString();
        }
    }

    public enum Currency {
        EUR, GBP, PLN
    }

    public class Country {
        private String name;
        private String capital;
        private Currency currency;

        public String getName() {
            return name;
        }

        public void setName(String value) {
            this.name = value;
        }

        public String getCapital() {
            return capital;
        }

        public void setCapital(String value) {
            this.capital = value;
        }

        public Currency getCurrency() {
            return currency;
        }

        public void setCurrency(Currency value) {
            this.currency = value;
        }

    }

}

3、在resources目录下创建一个countries.xsd文件,定义数据格式:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:tns="http://spring.io/guides/gs-producing-web-service"
           targetNamespace="http://spring.io/guides/gs-producing-web-service"
           elementFormDefault="qualified">

    <xs:element name="getCapitalRequest">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="arg0" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:element name="getCapitalResponse">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="return" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:element name="getCurrencyRequest">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="arg0" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:element name="getCurrencyResponse">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="return" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    
</xs:schema>

4、启动项目,并使用SOAPUI等工具进行接口测试。

三、RESTful协议下的Web Service接口调用

1、首先,在pom.xml中加入以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web-services</artifactId>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.1</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.11.1</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
    <version>2.11.1</version>
</dependency>

2、定义一个Controller类,实现接口方法:

@RestController
public class CountryController {

    private Map<String, Country> countries = new HashMap<>();

    public CountryController() {
        Country spain = new Country();
        spain.setName("Spain");
        spain.setCapital("Madrid");
        spain.setCurrency(Currency.EUR);
        countries.put(spain.getName(), spain);

        Country poland = new Country();
        poland.setName("Poland");
        poland.setCapital("Warsaw");
        poland.setCurrency(Currency.PLN);
        countries.put(poland.getName(), poland);

        Country uk = new Country();
        uk.setName("United Kingdom");
        uk.setCapital("London");
        uk.setCurrency(Currency.GBP);
        countries.put(uk.getName(), uk);
    }

    @RequestMapping(value = "/capital/{name}", method = RequestMethod.GET)
    public String getCapital(@PathVariable("name") String name) {
        return countries.get(name).getCapital();
    }

    @RequestMapping(value = "/currency/{name}", method = RequestMethod.GET)
    public String getCurrency(@PathVariable("name") String name) {
        return countries.get(name).getCurrency().toString();
    }

    public enum Currency {
        EUR, GBP, PLN
    }

    public class Country {
        private String name;
        private String capital;
        private Currency currency;

        public String getName() {
            return name;
        }

        public void setName(String value) {
            this.name = value;
        }

        public String getCapital() {
            return capital;
        }

        public void setCapital(String value) {
            this.capital = value;
        }

        public Currency getCurrency() {
            return currency;
        }

        public void setCurrency(Currency value) {
            this.currency = value;
        }

    }
}

3、启动项目,使用Postman等工具进行接口测试。

四、总结

在Spring Boot中,可以很方便地实现SOAP和RESTful协议下的Web Service接口调用。选择哪种协议,需要根据具体的需求和业务情况进行分析和选择。