Springboot实现累加器
时间: 2024-02-02 07:37:57 浏览: 27
以下是使用Springboot实现累加器的示例代码:
1. 创建累加器Controller
```java
@RestController
public class AccumulatorController {
private int count = 0;
@GetMapping("/count")
public int getCount() {
return count;
}
@PostMapping("/increment")
public int incrementCount() {
count++;
return count;
}
}
```
2. 测试累加器
使用浏览器或Postman发送GET请求到`/count`可以获取当前累加器的值,发送POST请求到`/increment`可以使累加器的值加1。
```java
public class AccumulatorControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testAccumulator() throws Exception {
mockMvc.perform(post("/increment"))
.andExpect(status().isOk())
.andExpect(content().string("1"));
mockMvc.perform(post("/increment"))
.andExpect(status().isOk())
.andExpect(content().string("2"));
mockMvc.perform(get("/count"))
.andExpect(status().isOk())
.andExpect(content().string("2"));
}
}
```
以上就是使用Springboot实现累加器的示例代码。