项目创建
点击Create New Project选择Spring Initializr并Next
我们当前需要新建的是Web项目,就选择Web下的Web项目并Next后Finish。
代码编写
创建包及类如下 Count:
package com.example.bean;
public class Count {
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
ResourceController:
package com.example.controller;
import com.example.bean.Count;
import com.example.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
public class ResourceController {
@Autowired
ResourceService resourceService;
@PutMapping(value = "/me/count")
@ResponseBody
public int initCount(@RequestBody Count count){
return resourceService.initCount(count);
}
@PostMapping(value = "/me/count")
@ResponseBody
public int modifyCount(@RequestBody Count count){
return resourceService.addCount(count);
}
@GetMapping(value = "/me/count")
@ResponseBody
public Count getCount()
{
return resourceService.getCount();
}
}
ResourceService:
package com.example.service;
import com.example.bean.Count;
import com.example.manager.ResourceManager;
import org.springframework.stereotype.Service;
@Service
public class ResourceService {
public int addCount(Count count){
if (count != null){
return ResourceManager.getInstance().addCount(count.getCount());
}
return 0;
}
public int minusCount(Count count){
if (count != null) {
return ResourceManager.getInstance().minusCount(count.getCount());
}
return 0;
}
public Count getCount()
{
Count count = new Count();
count.setCount(ResourceManager.getInstance().getCount());
return count;
}
public int initCount(Count count){
if (count != null) {
return ResourceManager.getInstance().initCount(count.getCount());
}
return 0;
}
}
ResourceManager:
package com.example.manager;
public class ResourceManager {
private int count = 0;
private static ResourceManager instance = new ResourceManager();
private ResourceManager(){}
public static ResourceManager getInstance(){
return instance;
}
public synchronized int addCount(int i){
count = count + i;
return count;
}
public synchronized int minusCount(int i){
count = count -i;
return count;
}
public int getCount(){
return count;
}
public int initCount(int i){
count = i;
return count;
}
}
注: synchronized是Java中的关键字,是一种同步锁。它修饰的对象有以下几种:
1. 修饰一个代码块,被修饰的代码块称为同步语句块,其作用的范围是大括号{}括起来的代码,作用的对象是调用这个代码块的对象; 2. 修饰一个方法,被修饰的方法称为同步方法,其作用的范围是整个方法,作用的对象是调用这个方法的对象; 3. 修改一个静态的方法,其作用的范围是整个静态方法,作用的对象是这个类的所有对象; 4. 修改一个类,其作用的范围是synchronized后面括号括起来的部分,作用主的对象是这个类的所有对象。 更多详情:https://www.cnblogs.com/weibanggang/p/9470718.html
启动服务
测试
测试工具:postman 查询接口,服务启动,count默认就是0: 使用put初始化:
再使用get查询: post接口:
再使用get查询:
|