写一个spring工程里将jar包里的共通方法服务化的代码
时间: 2024-06-10 13:09:18 浏览: 15
很高兴为您服务!以下是将jar包里的共通方法服务化的代码示例:
1. 在spring工程中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
```
2. 创建一个接口,定义服务方法:
```java
public interface CommonService {
public String commonMethod(String param);
}
```
3. 创建一个实现类,实现接口中的服务方法:
```java
@Service
@WebService(serviceName = "CommonService")
public class CommonServiceImpl implements CommonService {
@Override
public String commonMethod(String param) {
// 调用jar包中的共通方法
String result = CommonUtil.commonMethod(param);
return result;
}
}
```
4. 在启动类中添加以下注解,发布服务:
```java
@EnableWs
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
@Bean
public ServletRegistrationBean<MessageDispatcherServlet> messageDispatcherServlet() {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(new AnnotationConfigApplicationContext());
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean<>(servlet, "/ws/*");
}
@Bean(name = "CommonService")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema commonSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("CommonServicePort");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition.setTargetNamespace("http://example.com/common");
wsdl11Definition.setSchema(commonSchema);
return wsdl11Definition;
}
@Bean
public XsdSchema commonSchema() {
return new SimpleXsdSchema(new ClassPathResource("common.xsd"));
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
5. 创建common.xsd文件,定义服务的XML Schema:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://example.com/common"
targetNamespace="http://example.com/common"
elementFormDefault="qualified">
<xs:element name="commonMethodRequest" type="tns:commonMethodRequest"/>
<xs:element name="commonMethodResponse" type="tns:commonMethodResponse"/>
<xs:complexType name="commonMethodRequest">
<xs:sequence>
<xs:element name="param" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="commonMethodResponse">
<xs:sequence>
<xs:element name="result" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
```
6. 使用SOAPUI或浏览器访问http://localhost:8080/ws/CommonService.wsdl查看服务的WSDL定义。
希望这个代码示例能够帮助您!如果您有其他问题,请随时提出。