提问人:David Jackson 提问时间:2/25/2020 最后编辑:Vy DoDavid Jackson 更新时间:2/25/2020 访问量:175
Spring Boot CRUD 操作,用于创建 Web 服务配置
Spring Boot CRUD operation to create web service configuration
问:
我是使用 Spring Boot 的新手。我正在尝试为 CRUD 操作创建一个 restful Web 服务。
我创建了模型、存储库和以下文件: 服务文件:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EmployeeServiceApplication {
public static void main(String[] args) {
SpringApplication.run(EmployeeServiceApplication.class, args);
}
}
控制器文件:
@RestController
public class Controller {
@Autowired
private EmployeeServiceDesc employeeService;
@GetMapping("/employee/")
public List<Employee> getAllEmployees() {
return employeeService.getAllEmployees();
}
@GetMapping("/employee/{employeeId}")
public Employee getEmployeeById(@PathVariable int employeeId) {
return employeeService.getEmployeeById(employeeId);
}
@PostMapping("/employee/")
public ResponseEntity<Void> add(@RequestBody Employee newEmployee, UriComponentsBuilder builder) {
Employee employee = employeeService.addEmployee(newEmployee);
if(employee == null) {
return ResponseEntity.noContent().build();
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(builder.path("/employee/{id}").buildAndExpand(employee.getId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
@PutMapping("/employee/")
public ResponseEntity<Employee> updateEmployee(@RequestBody Employee v) {
Employee employee = employeeService.getEmployeeById(v.getId());
if(employee == null) {
return new ResponseEntity<Employee>(HttpStatus.NOT_FOUND);
}
employee.setName(employee.getName());
employee.setDOB(employee.getDOB());
employee.setSalary(employee.getSalary());
employeeService.updateEmployee(employee);
return new ResponseEntity<Employee>(employee, HttpStatus.OK);
}
@DeleteMapping("/employee/{id}")
public ResponseEntity<Employee> deleteEmployee(@PathVariable int id) {
Employee employee = employeeService.getEmployeeById(id);
if(employee == null) {
return new ResponseEntity<Employee>(HttpStatus.FOUND);
}
employeeService.deleteEmployee(id);
return new ResponseEntity<Employee>(HttpStatus.NO_CONTENT);
}
}
当我通过Postman发送请求时,出现错误:未找到 我想我缺少一些配置,但不确定我应该做什么?谁能帮我解决这个问题?
答:
0赞
Dulaj Kulathunga
2/25/2020
#1
你应该有如下的东西(你应该有映射请求)
@RestController
@RequestMapping("/")
public class Controller {
......
....
..
}
@RestController
@RequestMapping("/api")
public class Controller {
}
评论后不起作用
spring-boot 将扫描 com.x.x 以下包中的组件,因此如果您的控制器位于 com.x.x 中,则需要显式扫描它
@SpringBootApplication
@ComponentScan(basePackageClasses = Controller.class) // you should be able to justified as your packages structure
public class EmployeeServiceApplication {
public static void main(String[] args) {
SpringApplication.run(EmployeeServiceApplication.class, args);
}
}
评论
0赞
Dulaj Kulathunga
2/25/2020
你能试试我在评论后更新了代码吗?
0赞
KevinPB
2/25/2020
#2
您不一定需要@RequestMapping才能公开您的服务。我相信这里的问题是因为映射末尾的“/”。尝试将
@GetMapping("/employee/")
跟
@GetMapping("/employee")
评论