赞
踩
1.下载并安装Intellij idea.
2.选择Create New Project
3勾选左侧的Spring Initializr ,点击next
4.填写项目名称和包名,点击next
5.勾选左侧web ,然后勾选中间的sping web,点击右侧的next
6.等待项目创建完成。
实现接口
实现一个获取单条用户信息的接口 getUserItem,访问地址为 http://localhost:8080/getUserItem。
- package com.example.demo.entity;
- public class User {
- String name;
- int password;
- public String getName(){
- return name;
- }
- public void setName(String name){
- this.name = name;
- }
- public int getPassword(){
- return password;
- }
- public void setPassword(String password){
- this.password = password;
- }
- public String toString(){
- return "user{name='"+name+"\',"+"password="+password+"}";
- }
- }

- package com.example.demo.service;
- import com.example.demo.entity.User;
- public interface UserService {
- public User getUserInfo();
- }
随后在 service 文件包中新建 impl 文件包,在 impl 文件包中新建 UserServiceImpl 来实现 UserService 接口,内容如下:
- package com.example.demo.service.impl;
- import com.example.demo.entity.User;
- import com.example.demo.service.UserService;
- import org.springframework.stereotype.Service;
-
- @Service
- public class UserServiceImpl implements UserService {
- public User getUserInfo(){
- User user = new User();
- user.setName("jack");
- user.setPassword(12341234);
- return user;
- }
- }
- package com.example.demo.controller;
-
- import com.example.demo.entity.User;
- import com.example.demo.service.UserService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RestController;
-
- @RestController
- public class UserController {
- @Autowired
- UserService service;
- @RequestMapping(value = "/getUserItem",method = RequestMethod.GET)
- public String getUserItem(){
- User user = service.getUserInfo();
- return user.toString();
- }
- }

验证接口
执行主函数
在实现接口的过程中,需要在项目目录下,新建三个文件包:
entity 包,也就是实体类,这里存放业务逻辑所需要的对象属性或方法。比如要获取用户信息,而用户信息包含名称和密码这两个属性,就需要在这里定义和创建,并同时定义 set 方法用于赋值,定义 get 方法用于取值。
service 包,也就是提供服务的类,有了对象,接下来就要使用对象,实现功能,定义接口。定义接口之后还需要一个实现类,来实现接口。
controller 包,提供了服务之后就要开始使用服务,也就是调用服务类所提供的方法来返回最终的数据。
1.打开右侧的Maven,选择package打出jar包
2.打开cmd ,打开jar包所在的文件夹
3.输入java -jar jar包名称
4.回车等待jar发布
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。