SpringBoot学习总结

SpringBoot学习小总结

SpringBoot入门

为什么用SpringBoot:

​ Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”.

能快速创建出生产级别的Spring应用

SpringBoot优点:

1、创建独立的Spring应用 -一键打包

2、内嵌Web服务器 - 无需安装tomcat

3、starter简化配置 - 依赖管理简单

4、自动配置了Spring和第三方功能 - 不用再配置了

5、提供生产级别监控、健康检查以及外部化配置 - 还不知道是什么东西

6、无代码,xml生成 - 简洁直观,阅读性强

总结:程序员更需关注业务,而不是繁缛的xml配置和tomcat环境配置等工作。

SpringBoot的注解有哪些?作用是啥?
  • @Configuration - 通过方法给容器中注册bean,方法名就是组件id

    (Full)proxyBeanMethods = true - 该配置类本身也是组件,用代理方式加载该配置类。会在每次执行方法时检查容器中是否有该bean 在方法中的组件有依赖时使用这种模式

    (Lite)proxyBeanMethods = false - 加载时无需检查 无依赖时使用这种模式,提高启动效率

  • @Import - 容器自动创建该类型组件,默认组件名就是全类名

  • @Conditional - 满足条件才进行组件注入

    • @ConditionalOnMissingBean
    • @ConditionalOnBean
  • @ConfigurationProperties - 引入配置文件,并注入到该注解所注解的类中

    1、只有注入到容器中的组件,才能使用这个注解

    2、如果该类是一个外部的类,且类上添加了@ConfigurationProperties,可以在其它配置类上加 @EnableConfigurationProperties(xxx.class)

    ​ 代表:

    ​ 1、将该类生成实例并注册组件到容器

    ​ 2、开启该组件的配置绑定功能

    case : @ConfigurationProperties(prefix = “mycar”)

  • @ImportResource - 把原生xml注入的容器注入

    case : @ImportResource(“classpath:beans.xml”)

  • @SpringBootApplication - 代表这是一个SpringBoot项目

    • @SpringBootConfiguration - 代表这是个配置类

    • @EnableAutoConfiguration - 自动配置的核心

      • @Import(AutoConfigurationImportSelector.class) - AutoConfigurationImportSelector从 META/INF下获取到spring.factories下的org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 下的所有类名 , 并将它们加载到容器中
      • @AutoConfigurationPackage 获取到当前元注解所在类的所在包路径(该理解是否正确未知)
    • @ComponentScan - 扫描包里面被@Component等注释的组件

      在这里插入图片描述

      开发技巧:
      • lombock
        • @NoArgsConstructor
        • @AllArgsConstructor
        • @Data
        • @ToString
        • @EqualsAndHashCode
        • @Slf4j //简化日志开发
      • dev-tools - 假的热启动(没啥用)
      • Spring Initailizr 开发脚手架
      配置文件:

      ​ yaml:

      对象:
      行内写法:  k: {k1:v1,k2:v2,k3:v3}
      #或
      k: 
        k1: v1
        k2: v2
        k3: v3
        
      数组:  
      行内写法:  k: [v1,v2,v3]
      #或者
      k:
       - v1
       - v2
       - v3
      

      自定义配置文件提示:

      <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-configuration-processor</artifactId>
                  <optional>true</optional>
              </dependency>
      
      
       <build>
              <plugins>
                  <plugin>
                      <groupId>org.springframework.boot</groupId>
                      <artifactId>spring-boot-maven-plugin</artifactId>
                      <configuration>
                          <excludes>
                              <exclude>
                                  <groupId>org.springframework.boot</groupId>
                                  <artifactId>spring-boot-configuration-processor</artifactId>
                              </exclude>
                          </excludes>
                      </configuration>
                  </plugin>
              </plugins>
          </build>
      

      SpringBoot-Web

      静态资源:

      直接访问SpringBoot项目的地址就可以直接访问的路径

      默认路径:/static(or/publicor/resourcesor/META-INF/resources

      访问顺序:先访问Controller,再访问静态资源

    #改变前缀
    spring:
      mvc:
        static-path-pattern: /res/**
    #改变静态资源路径
      resources:
        static-locations: [classpath:/haha/]	
    

    ​ 1、项目路径/和/index默认访问index.html

    ​ 2、springboot2.4有bug,改变前缀后无法访问到欢迎页

    Favicon:

    ​ 1、把favicon.ico放在静态资源路径即可

    ​ 2、同理,springboot2.4有bug,改变前缀后无法访问到favicon.ico

    请求参数相关
    相关注解:(重点)

    ​ @PathVariable:

    ​ 1、来自路径

    ​ 2、可用 Map<String,String> 接收

    ​ @RequestHeader:

    ​ 1、来自请求头

    ​ 2、可用Map<String,String>接收

    ​ @RequestParam:

    ​ 1、来自urlencoded或json的请求体

    ​ 2、可用 Map<String,String> 接收

    ​ @requestBody:

    ​ 当Content-Type为以下值时控制器的接收情况:

    ​ application/x-www-form-urlencoded - 只能用String接收

    ​ application/json - 可用对象接收,会自动装配 可用String接 可用Map<String,String>接收

    ​ application/form-data - 不可接收

    ​ @CookieValue:

    ​ 1、用Cookie接收

    ​ 2、用String接收,接收到单个cookie

    ​ @MatrixVariable:

    ​ 矩阵变量

    ​ 1、用于区分路径和其它变量,比如说cookie禁用时可以传cookie

    ​ 2、使用时,重定义configurePathMatch。

    ​ 3、使用时,需绑定pathVarible才能使用。

    ​ 4、用的少,不深入

      
      
      
      //请求路径:/cars/sell;low=34;brand=byd,audi,yd
      @GetMapping("/cars/{path}")
        public Map carsSell(@MatrixVariable("low",pathVar = "path") Integer low,
                            @MatrixVariable("brand",pathVar = "path") List<String> brand,
                            @PathVariable("path") String path){
            Map<String,Object> map = new HashMap<>();
    
            map.put("low",low);
            map.put("brand",brand);
            map.put("path",path);
            return map;
        }
        
        
    
    对原生servlet api的支持:(现实中不常用)

    ​ WebRequest、ServletRequest、MultipartRequest、 HttpSession、javax.servlet.http.PushBuilder、Principal、InputStream、Reader、HttpMethod、Locale、TimeZone、ZoneId

复杂参数:

​ Model ,ModelAndView,ModelMap - 大同小异,都是取requset域的值

​ RedirectAttributes,HttpSession - session域的值

​ HttpServletRequest - request session都能获取。

​ 模板引擎模式下的返回值:

​ 重定向:return “redirect:/xxx”;

​ 转发: return “xxx”;

tymeleaf:

​ 1、模板引擎,类似于jsp

​ 2、springboot原生支持,也就是说SpringBoot中有这个东西的自动配置类,引入依赖即可使用:

​ 配置好了 SpringTemplateEngine —这玩意不知道是什么,有空研究下

​ 配好了 ThymeleafViewResolver

拦截器:

​ 编写一个拦截器的过程:

​ 1、编写一个类实现 HandlerInterceptor

​ 2、重写preHandle()方法, postHandle ()方法,afterCompletion()方法

​ preHandle -> controller -> postHandle -> afterCompletion

​ 在异常没有被catch的情况下:

​ 1、preHandle异常直接出去

​ 2、controller和postHandle异常进入afterCompletion

​ 3、在继承WebMvcConfigure上的类重写addInterceptors()方法

​ case:

@Configuration
public class AdminWebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")  //所有请求都被拦截包括静态资源
                .excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**","/js/**"); //放行的请求
    }
}
文件上传 :
  1. MultipartFile 或 MultipartFile[]接收
  2. multipartfile.transferTo( (new File(“H:\cache\”+multipartfile.getOriginalFilename())); ) - 一个比较有用的方法,直接输出的文件夹了
异常处理:
  1. 默认提供/error处理错误
  2. 机器客户端提供whitelabel视图
  3. 可以把4xx,5xx的页面放到/error下,自动映射到这个页面。
  4. 可以取到requst域中的key为error的值,然后渲染到模板中。
Web原生组件注入:(个人感觉不常用,了解)
  1. 使用Servlet API

    @ServletComponentScan(basePackages = “com.atguigu.admin”) :指定原生Servlet组件都放在那里

    @WebServlet(urlPatterns = “/my”):效果:直接响应,没有经过Spring的拦截器?

    @WebFilter(urlPatterns={"/css/*","/images/*"})

    @WebListener

  2. 使用ServletRegistrationBean,FilterRegistrationBean,ServletListenerRegistrationBean方法注册组件。

DelegatingWebMvcConfiguration:

@EnableWebMvc + WebMvcConfigurer(慎用):可全方位重定制springmvc,因为@EnableWebMvc引入了DelegatingWebMvcConfiguration,而WebMvcAutoConfiguration上面@ConditionalOnMissingBean(WebMvcConfigurationSupport.class),

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值