首页 > 其他分享 >Spring Boot 3太强:全新Controller接口定义方式

Spring Boot 3太强:全新Controller接口定义方式

时间:2024-06-05 17:33:27浏览次数:16  
标签:PersonService 定义 Spring Boot 接口 class Person Controller public

环境:SpringBoot3.2.5


1. 回顾定义接口方式

1.1 常规定义

@RestController
@RequestMapping("/users")
public class UsersController {
  @PostMapping()
  public Object save(@RequestBody Users users) {
    // ...
  }
}

99.9999%的人都是这样定义接口。

1.2 好奇定义


@Component("/games/api")
public class CustomController implements Controller {

  @Override
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setContentType("text/html;charset=utf8");
    PrintWriter out = response.getWriter() ;
    out.print("<h1>Controller接口</h1>") ;
    out.close() ;
    return null ;
  }
}

这也就是看到时学习下,谁会用到工作中?

1.3 装逼定义


@Component("/zhuangbi/api")
public class ControllerHttpRequestHandler implements HttpRequestHandler {
  public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=utf8");
    PrintWriter out = response.getWriter() ;
    out.print("<h1>你好,HttpRequestHandler</h1>") ;
    out.close() ;
  }
}

这不就是在写Servlet吗!谁还记得如何编写Servlet?

以上是在Spring MVC中定义API接口的几种方式(纯Servlet就算了)。接下来我将介绍另外一种定义Controller接口的方式。

注意:接下来定义接口的方式需要在Spring6.0以上版本

2. 新的定义方式

从Spring6开始新增了一个新注解@HttpExchange。该注解将一个类或具体方法声明为HTTP 接口。接口的细节通过注解的属性以及方法参数定义。如下示例:

声明接口


@HttpExchange("/persons")
interface PersonService {

  @GetExchange("/{id}")
  Person getPerson(@PathVariable Long id);

  @PostExchange
  void add(@RequestBody Person person) ;
}
// Person对象
public class Person {
  private Long id ;
  private String name ;
  // getters, setters
}

实现接口


@RestController
public class PersonController implements PersonService {

  public Person getPerson(@PathVariable Long id) {
    return new Person(id, "姓名 - " + id) ;
  }

  @ResponseStatus(HttpStatus.CREATED)
  public void add(@RequestBody Person person) {
    // TODO
  }
}

在该实现类上与普通Controller声明一样使用@RestController注解。

除了上面使用的@GetExchange@PostExchange,还有下面这几个注解:

  • @DeleteExchange

  • @PatchExchange

  • @PutExchange

与@RequestMapping一样,这里的@HttpExchange注解也可以直接使用到方法上,如下:


@HttpExchange(value = "/list", method = "GET")
default List<Person> listPerson() {
  return List.of(new Person(666L, "李四")) ;
} ;

在接口中声明一个默认的方法。

3. @HttpExchange真正目的

@HttpExchange的主要目的是使用生成的代理抽象HTTP客户端代码。如下示例

还是使用上面的PersonService接口定义,通过该接口生成代理类


@Configuration
public class PersonServiceClient {

  @Bean
  PersonService personServiceProxy() {
    RestClient restClient = RestClient.builder().baseUrl("http://localhost:8088").build();
    RestClientAdapter adapter = RestClientAdapter.create(restClient);
    HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();

    PersonService personService = factory.createClient(PersonService.class);
    return personService ;
  }

}

PersonService创建代理对象,通过JDK代理。注意:这里的RestClient必须使用Spring6.1以上版本,如果你不是那你可以换成RestTemplate.


@Resource
private PersonService personServiceProxy ;
@GetMapping("/persons")
public List<Person> list() {
  return this.personServiceProxy.listPerson() ;
}

目标服务接口如下:


@GetMapping("/persons/list")
public List<Person> list() {
  return Arrays.asList(
        new Person(1L, "张三", 20, "[email protected]"),
        new Person(2L, "李四", 25, "[email protected]"),
        new Person(3L, "王五", 55, "[email protected]")
      ) ;
}

输出结果

标签:PersonService,定义,Spring,Boot,接口,class,Person,Controller,public
From: https://blog.csdn.net/weixin_53391173/article/details/139422498

相关文章

  • Spring Boot集成RocketMQ实现分布式事务
            RocketMQ是由阿里巴巴集团开发的一款高性能、高可靠、分布式的开源消息中间件,它在2012年对外开源,并于2016年捐赠给Apache软件基金会,随后在2017年成为了Apache的顶级项目。RocketMQ的设计旨在满足互联网业务场景中的海量消息传递需求,尤其擅长处理高并发、大数据......
  • 灵动微电子 MM32F5277 boot分区实现之Flash驱动移植(二)
    前言    上篇文章,我们移植了nr_micro_shell串口shell组件到MM32F5277上,在此基础上,我们继续移植NorFlash和EmbddedFlash的驱动,并编写串口命令进行测试!NorFlash驱动移植    我们先到灵动微的官网下载官方的SDK,贴个官网链接:灵动微电子SDK下载https://mind......
  • Spring家族中的消息通信解决方案
    相信大家对消息通信架构以及各种消息中间件应该都不陌生。在分布式系统的设计和开发过程中,消息通信是用于实现系统解耦、提高扩展性的一大技术体系。而业界关于如何实现消息通信系统也有很多解决方案和对应的开发框架。不知道你有没有发现,在我们每天都在使用到Spring框架中,实际......
  • spring入门aop和ioc
    目录spring分层架构表现层服务层(业务层)持久层spring核心ioc(控制反转)1)接下来是代码示例:2)ioc容器的使用过程3)ioc中的bean管理4)实例化bean的三种方式aop(面向切面开发)定义优势AOP底层原理AOP相关的术语AOP入门aop注解开发aop纯注解开发Di(依赖注入)1)属性的set方法注入值的方式2)构造......
  • springMvc 配置 UReport2
    参考:https://blog.csdn.net/qq_42207808/article/details/112258835 1.配置pom.xml引入目前最新得2.2.9版本<dependency><groupId>com.bstek.ureport</groupId><artifactId>ureport2-console</artifactId&......
  • 基于SpringBoot的秒杀系统源码数据库
    基于SpringBoot的秒杀系统源码数据库社会发展日新月异,用计算机应用实现数据管理功能已经算是很完善的了,但是随着移动互联网的到来,处理信息不再受制于地理位置的限制,处理信息及时高效,备受人们的喜爱。本次开发一套基于SpringBoot的秒杀系统,管理员功能有个人中心,用户管理,商品类......
  • 基于springboot的二手车交易系统源码数据库
    基于springboot的二手车交易系统源码数据库如今社会上各行各业,都喜欢用自己行业的专属软件工作,互联网发展到这个时候,人们已经发现离不开了互联网。新技术的产生,往往能解决一些老技术的弊端问题。因为传统二手车交易信息管理难度大,容错率低,管理人员处理数据费工费时,所以专门为......
  • 基于springboot的纺织品企业财务管理系统源码数据库
    基于springboot的纺织品企业财务管理系统源码数据库在如今社会上,关于信息上面的处理,没有任何一个企业或者个人会忽视,如何让信息急速传递,并且归档储存查询,采用之前的纸张记录模式已经不符合当前使用要求了。所以,对纺织品企业财务信息管理的提升,也为了对纺织品企业财务信息进行......
  • 一个基于 React + SpringBoot 的在线多功能问卷系统(附源码)
    简介:一个基于React+SpringBoot的在线多功能问卷系统前端技术栈:React、React-Router、Webpack、Antd、Zustand、Echarts、DnDKit后端技术栈:SpringBoot、MySQL、MyBatisPlus、Redis项目源码下载链接: https://pan.quark.cn/s/2e32786e0c61部分页面静态预览: 主要前......
  • 基于springboot实现疫情信息管理系统项目【项目源码+论文说明】计算机毕业设计
    基于springboot实现疫情信息管理系统演示摘要近年来,信息化管理行业的不断兴起,使得人们的日常生活越来越离不开计算机和互联网技术。首先,根据收集到的用户需求分析,对设计系统有一个初步的认识与了解,确定疫情信息管理系统的总体功能模块。然后,详细设计系统的主要功能模块,通......