使用idea开发工具,基于Maven环境进行Spring集成CXF WebService框架。
1、pom.xml文件添加依赖包:
junit
junit
3.8.1
org.springframework
spring-context
4.3.7.RELEASE
org.springframework
spring-web
4.3.7.RELEASE
org.apache.cxf
cxf-rt-frontend-jaxws
3.1.10
org.apache.cxf
cxf-rt-transports-http
3.1.10
2、创建实体:
public class User {
private String username;
private int age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
3、创建webService接口:
@WebService
public interface IUserService {
//新增
@WebMethod
public void addUser(User user);
//获取所有
@WebMethod
public ListfindAll();
}
4、接口实现类:
@Service
public class IUserServiceImpl implements IUserService {
@Autowired
private IUserDao userDao;
public void addUser(User user) {
userDao.save(user);
}
public ListfindAll() {
return userDao.findAll();
}
}
5、持久层接口:
public interface IUserDao {
//保存
void save(User user);
//获取所有
ListfindAll();
}
6、持久层实现:
@Repository
public class IUserDaoImpl implements IUserDao {
private ArrayListusers = new ArrayList();
public void save(User user) {
users.add(user);
}
public ListfindAll() {
return users;
}
}
7、编辑spring配置文件,配置注解扫描和发布webService服务:
8、修改web.xml配置文件:
contextConfigLocation
classpath*:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
CXFServlet
org.apache.cxf.transport.servlet.CXFServlet
CXFServlet
/service/*
10、启动项目,进行测试:
访问路径: http://localhost:8080/spring_cxf/service,获取该路径所有的服务列表
点击WSDL后面的连接,查看wsdl文件内容。
11、创建测试客户端:
使用CXF提供的“wsdl2java.bat”工具,根据WSDL创建java客户端代码:
12、复制生成的java代码到项目中。
13、编写客户端测试代码。
public class Demo {
@Test
public void add(){
IUserServiceService userServiceService = new IUserServiceService();
IUserService userService = userServiceService.getIUserServicePort();
User user = new User();
user.setUsername("lisi");
user.setAge(5);
userService.addUser(user);
System.out.println("新增结束");
}
@Test
public void findAll(){
IUserServiceService userServiceService = new IUserServiceService();
IUserService userService = userServiceService.getIUserServicePort();
Listusers = userService.findAll();
for(User u : users){
System.out.println("username = "+u.getUsername()+" age = "+ u.getAge());
}
}
}
14、源码下载地址:http://download.csdn.net/detail/mmd0308/9819309