使用IDEA创建一个Spring Boot项目
首先创建项目
然后勾选Spring Initializer
完善项目信息,组名可不做修改,项目名可做修改;
Web下勾选Spring Web Start,(网上创建springboot项目多是勾选Web选项,而较高版本的Springboot没有此选项,勾选Spring Web Start即可,2.1.8版本是Spring Web);Template Englines勾选Thymeleaf;SQL勾选:MySQL Driver,JDBC API 和 MyBatis Framework三项;点击next;
选择项目路径,点击finish;打开新的窗口;
刚创建好的项目目录结构
点击右侧的Maven,点击设置(扳手图标)进行项目Maven仓库的配置;
在templates文件下新建index.html页面,作为启动的初始页面;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
你好!初学者,我是SpringBoot的简单启动页面!
</body>
</html>
运行效果如下:
RESTful 接口的 Web服务
首先在java/com.example.demo下创建四个包
分别命名为bean,controller,manager,service。分别代表了实体层,控制层,管理层和服务层
在每个包中创建相应的类,并编写代码
代码:
Count:
package com.example.demo.bean;
public class Count {
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
ResourceController:
import com.example.demo.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
public class ResourceController {
@Autowired
ResourceService resourceService;
@RequestMapping(value = "/me/count", method = RequestMethod.PUT)
@ResponseBody
public void initCount(@RequestBody Count count){
resourceService.initCount(count);
}
@RequestMapping(value = "/me/count", method = RequestMethod.POST)
@ResponseBody
public void modifyCount(@RequestBody Count count){
resourceService.addCount(count);
}
@RequestMapping(value = "/me/count", method = RequestMethod.GET)
@ResponseBody
public Count getCount()
{
return resourceService.getCount();
}
}
ResourceManager:
package com.example.demo.manager;
public class ResourceManager {
private int count = 0;
private static ResourceManager instance = new ResourceManager();
private ResourceManager(){}
public static ResourceManager getInstance(){
return instance;
}
public synchronized void addCount(int i){
count = count + i;
}
public synchronized void minusCount(int i){
count = count -i;
}
public int getCount(){
return count;
}
public void initCount(int i){
count = i;
}
}
ResourceService:
package com.example.demo.service;
import com.example.demo.bean.Count;
import com.example.demo.manager.ResourceManager;
import org.springframework.stereotype.Service;
@Service
public class ResourceService {
public void addCount(Count count){
if (count != null){
ResourceManager.getInstance().addCount(count.getCount());
}
}
public void minusCount(Count count){
if (count != null) {
ResourceManager.getInstance().minusCount(count.getCount());
}
}
public Count getCount()
{
Count count = new Count();
count.setCount(ResourceManager.getInstance().getCount());
return count;
}
public void initCount(Count count){
if (count != null) {
ResourceManager.getInstance().initCount(count.getCount());
}
}
}
在helloworldApplication上右键启动,效果如下:
测试:
服务提供了三个接口:
URL都是:/me/count 只是分PUT、POST和GET,其中PUT用于初始化,POST用于修改(这里修改是累加),GET用于查询。
下面使用POSTMan进行测试:
查询接口,服务启动,count默认就是0: