Spring MVC 5.2起提供一種輕量級functional programing model的方式來處理Web請求,就讓我們來看看有別於Controller+RequestMapping的方式吧
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(){
return "Hello";
}
}
Bean
@Data
@AllArgsConstructor
public class Person {
private String name;
private String id;
}
Repository
@Slf4j
@Repository
public class PersonRepository {
public void create(Person person){
log.info("===Repository=== create person:"+person);
}
public Person findById(String id){
log.info("===Repository=== getPersonById:"+id);
return new Person("james","3");
}
public List<Person> findAll(){
log.info("===Repository=== findAll");
List<Person> list = new ArrayList<>();
Person p1 = new Person("p1","1");
Person p2 = new Person("p2","2");
list.add(p1);
list.add(p2);
return list;
}
public void update(Person person){
log.info("===Repository=== update;"+ person);
}
public void delete(String id){
log.info("===Repository=== delete;"+id);
}
}
Handler
@Component
public class PersonHandler {
// @Autowired
private PersonRepository personRepository;
public PersonHandler(PersonRepository personRepository) {
this.personRepository = personRepository;
}
public ServerResponse getPersonById(ServerRequest request) {
Person person = personRepository.findById(request.pathVariable("id"));
return ServerResponse.ok().body(person);
}
public ServerResponse updatePerson(ServerRequest request) throws ServletException, IOException {
Person person = request.body(Person.class);
personRepository.update(person);
return ServerResponse.ok().build();
}
public ServerResponse listPeople(ServerRequest request) {
List<Person> list = personRepository.findAll();
return ServerResponse.ok().body(list);
}
public ServerResponse createPerson(ServerRequest request) throws ServletException, IOException {
//提取请求体
Person body = request.body(Person.class);
personRepository.create(body);
return ServerResponse.ok().build();
}
public ServerResponse deletePerson(ServerRequest request) throws ServletException, IOException {
personRepository.delete(request.pathVariable("id"));
return ServerResponse.ok().build();
}
}
PersonRouterConfig,可以比較一下先前使用Controller + RequestMapping的方式
@Configuration
public class PersonRouterConfig {
@Bean
public RouterFunction<ServerResponse> routes(PersonHandler handler) {
return RouterFunctions.route(GET("/api/person"), handler::listPeople)
.andRoute(POST("/api/person"), handler::createPerson)
.andRoute(GET("/api/person/{id}"), handler::getPersonById)
.andRoute(PUT("/api/person/{id}"), handler::updatePerson)
.andRoute(DELETE("/api/person/{id}"), handler::deletePerson);
}
}
GET getPersonById
GET listPeople
POST createPerson
DELETE deletePerson