首页 > 编程语言 > 详细

SpringBoot学习

时间:2021-07-13 20:13:13      阅读:4      评论:0      收藏:0      [点我收藏+]

一、SpringBoot基础

1. 设计模式

将整个应用程序划分为三层架构:

  • 表现层(UI):MVC就在这一层,包括View、Model、Controller

  • 业务逻辑层(Service)

  • 数据持久化层(DAO)

2. 使用Controller

2.1 常用注解

  1. @Controller:定义一个控制器类,检测其中的方法是否使用@RequestMapping,不能返回json数据。必须要同时使用@RequestBody

  2. @RestController:等价于@Controller+@RequestBody的功能,用来标注Rest风格的控制器类,接口数据会被反序列化为JSON

  3. @RequestMapping:处理地址映射。用在类上表示类中的所有响应请求的方法都以该地址为父路径

    该注解可以指定的属性:

    1. value:请求的地址

    2. method:GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE

      有简写:

      1. @GetMapping("/"),等价于@RequestMapping(value="/", method=RequestMethod.GET);

      2. @PostMapping

      3. @DeleteMapping

      4. @PutMapping

    3. consumes:消费信息,指定处理请求的提交内容类型(content-type),例如application/json, text/html

      1. pc端网页常用text/html格式

      2. 手机app采用JSON格式

    4. produces:生产消息,指定返回的内容类型。

    5. params:指定requests中必须包含某些参数值才让该方法处理请求;

    6. headers:指定request中必须包含某些指定的header值才处理请求

    该注解可以对类或者对方法使用:

 1 @RestController
 2 @RequestMapping("news")
 3 Public class NewsController{
 4   //get
 5   @RequestMapping(value="/",method=RequestMethod.GET)
 6   public void add() {}
 7   
 8   //post
 9   @RequestMapping(value="/",method=RequestMethod.POST)
10   public void save(){}
11 }
12 
13 //使用以上代码,get和post方式访问add或者save方法的路径都是http://localhost:8080/news/
14 //虽然路径一样但http方法不一样,所以不冲突。

  4. @pathvariable:将请求url中的变量映射到参数上。

1 @RequestMapping(value="/product/{id}",method=RequestMethod.GET)
2 public String getProduct(@PathVariable("id") String id){
3     //用这个注解把url中的id拿到
4   Product product=productRepository.findById(id);
5   return "product/show";
6 }

2.2 处理http请求

1. GET

1 @GetMapping("/{id}")
2 public ModelAndView getArticle(@PathVariable("id") Integer id) throws Exception{
3   Article article=articleRepository.findById(id);
4   ModelAndView mav=new ModelaAndView("article/show");
5   mav.addObject("article",articles);
6   return mav;
7 }

其他HTTP方法都有类似的Mapping操作

2.3 获取url中的参数

  1. 使用@PathVariable 注解,对于/{id}形式的url可以获取;

  2. 写入方法的形参中,对于参数以=出现在url中的情况:

1 @RequestMapping("/addUser")
2 public String addUser(String username){
3   //...
4 }
5 //可以获取url参数如:
6 //http://localhost:8080/user/?username=xxxx

   3. Bean

1 public String addUser(userModel user)
  1. @ModelAttribute

  2. HttpServletRequest

  3. @RequestParam

  4. @ResponseBody接收JSON数据

  5. MultipartFile

3. model

数据库表对应的实体类,暂时将数据存储在内存中等待持久化。实体Bean

1 @Getter
2 @Setter
3 public class User{
4   private long id;
5   private String name;
6 }
7 //使用@Getter和@Setter注解会自动生成get和set方法

 

二、Restful接口风格

动作

普通CRUD的URL

普通CRUD的HTTP方法

Restful的URL

Restful的CRUD的http方法

查询

Article/id=1

GET

Article/{id}

GET

添加

Article/title=xxx&body=xxx

GET/POST

Article

POST

修改

Article/update?id=xxx

GET

Article/{id}

PUT/PATCH

删除

Article/delete?id=xxx

GET

Article{id}

DELETE

如果发现找不到常用的@RestController等注解,(例如从官网下载项目包),可以修改pom.xml中的脚手架org.spring-framework.boot-web,然后刷新maven重试。

1. Swagger_ui

可以展示api

1. 在pom.xml中添加依赖

 1 <!--file:pom.xml-->
 2 <!--Swagger依赖-->
 3         <dependency>
 4             <groupId>io.springfox</groupId>
 5             <artifactId>springfox-swagger2</artifactId>
 6             <version>2.9.2</version>
 7         </dependency>
 8         <!--Swagger-UI依赖 -->
 9         <dependency>
10             <groupId>io.springfox</groupId>
11             <artifactId>springfox-swagger-ui</artifactId>
12             <version>2.9.2</version>
13         </dependency>

2. swagger配置编写

 1 //file:config/SwaggerConfig
 2 /**
 3  * Swagger 配置文件
 4  */
 5 @Configuration
 6 public class SwaggerConfig {
 7     @Bean
 8     public Docket createRestApi() {
 9         return new Docket(DocumentationType.SWAGGER_2)
10                 .apiInfo(apiInfo())
11                 .select()
12                 .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
13 
14                 .paths(PathSelectors.any())
15                 .build();
16     }
17 
18     private ApiInfo apiInfo() {
19         return new ApiInfoBuilder()
20                 .title(" RESTful APIs")
21                 .description("RESTful APIs")
22                 .termsOfServiceUrl("http://localhost:8080/")
23                 .contact("long")
24                 .version("1.0")
25                 .build();
26     }
27 }

3. 更新启动类配置,加上注解@EnableSwagger2

三、SpringBoot+mybatis

1. mybatis简介

  • 什么是 MyBatis ?

  • Apahce的?个开源项?

  • 一款优秀的持久层框架,它?持?定义 SQL、存储过程以及高级映射,免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的?作,通过简单的 XML 或注解来配置和映射 Java对象到数据库中的记录

  • 官?地址:https://mybatis.org/mybatis-3/

  • 每个基于 MyBatis 的应用都是以?个SqlSessionFactory的实例为核?

  • SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得

  • SqlSessionFactoryBuilder 可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例

  • ?厂设计模式?面需要获取SqlSession ,?面提供了在数据库执? SQL 命令所需的所有?法

2. mybatis使用

2.1 demo项目结构

技术分享图片

2.2 dao层代码

 1 //net.xdclass.online_class.dao.VideoMapper
 2 package net.xdclass.online_class.dao;
 3 
 4 import net.xdclass.online_class.domain.Video;
 5 import org.apache.ibatis.annotations.Param;
 6 
 7 public interface VideoMapper {
 8     /**
 9      * 根据视频id查找视频对象
10      * @param videoId
11      * @return
12      */
13     Video selectById(@Param("video_id") int videoId);
14 }

2.3 mapper.xml代码,在这里写sql查询

 1 <!--
 2   resources/mapper/VideomMapper.xml
 3   -->
 4 <?xml version="1.0" encoding="UTF-8" ?>
 5 <!DOCTYPE mapper
 6         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 7         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 8 <!--
 9 namespace: 名称空间,一般需要保持全局唯一, 最好是和dao层的java接口一致,
10 可以映射 sql语句 到对应的方法名称和参数、返回类型
11 mybatis是使用接口动态代理
12 -->
13 <mapper namespace="net.xdclass.online_class.dao.VideoMapper">
14     <!--
15     statement sql
16     id: 当前mapper下需要唯一
17     resultType : sql查询结果集的封装
18     -->
19     <select id="selectById" resultType="net.xdclass.online_class.domain.Video">
20         select * from video where id = #{video_id}
21     </select>
22 </mapper>

2.4 mybatis使用:

 1 public class SqlSessionDemo {
 2     public static void main(String [] args) throws IOException {
 3         String resouce = "config/mybatis-config.xml";
 4         //读取配置文件
 5         InputStream inputStream =  Resources.getResourceAsStream(resouce);
 6 
 7         //构建Session工厂
 8         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 9 
10         //获取Session,jdk8语法
11         try(SqlSession sqlSession = sqlSessionFactory.openSession()){
12             VideoMapper videoMapper = sqlSession.getMapper(VideoMapper.class);
13             Video video = videoMapper.selectById(44);
14             //System.out.println(video.toString());
15 
16             //通过注解
17             //List<Video> videoList =  videoMapper.selectList();
18 
19             List<Video> videoList = videoMapper.selectListByXML();
20             System.out.println(videoList.toString());
21         }
22     }
23 }

四、SpringBoot使用定时任务和异步任务

1. 定时任务

2. 异步任务

五、SpringBoot进阶


to be continued~

 

SpringBoot学习

原文:https://www.cnblogs.com/gurui2333/p/15001457.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!