SpringBoot【原理分析、YAML文件、SpringBoot注册web组件】(二)-全面详解(学习总结---从入门到深化)

news2024/9/22 19:36:35

 

目录

 SpringBoot原理分析_核心注解

YAML文件_配置文件介绍 

YAML文件_自定义配置简单数据

 YAML文件_自定义配置对象数据

 YAML文件_自定义配置集合数据

YAML文件_读取配置文件的数据

使用@ConfigurationProperties读取

YAML文件_占位符的使用

YAML文件_配置文件存放位置及优先级

YAML文件_bootstrap配置文件

SpringBoot注册web组件_注册Servlet 

 SpringBoot注册web组件_注册Filter

SpringBoot注册web组件_注册Listener


 

 SpringBoot原理分析_核心注解

 @SpringBootApplication

标注是SpringBoot的启动类。 此注解等同于

@SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan 。

 @SpringBootConfiguration

@SpringBootConfiguration 是 @Configuration 的派生注解,跟 @Configuration 功能一 致,标注这个类是一个配置类,只不过 @SpringBootConfiguration 是 Springboot的注解,而 @Configuration 是Spring的注解

 @EnableAutoConfiguration

SpringBoot自动配置注解。 等同于

@AutoConfigurationPackage + @Import(AutoConfigurationImportSelector.class)

 @AutoConfigurationPackage

自动扫描包的注解,它会自动扫描主类所在包下所有加了注解的类 (@Controller,@Service等),以及配置类 (@Configuration)。

@Import({AutoConfigurationImportSelector.class})

该注解会导入 AutoConfifigurationImportSelector 类对象,该对象会从 META-INF/spring.factories 文件中读取配置类的名称列表。 

@ComponentScan

该注解会扫描项目,自动装配一些项目启动需要的Bean。 

YAML文件_配置文件介绍 

 SpringBoot项目中,大部分配置都有默认值,但如果想替换默认配 置的话,就可以使用application.properties或者application.yml进 行配置。

SpringBoot默认会从resources目录下加载application.properties 或application.yml文件。其中,application.properties文件是键值 对类型的文件,之前一直在使用,所以我们不再对properties文件 进行阐述。

 https://docs.spring.io/spring-boot/docs/2.7.0-M1/reference/ htmlsingle/#application-properties.server可以查找配置文件 如何覆盖SpringBoot项目的默认配置。

 除了properties文件外,SpringBoot还支持YAML文件进行配置。 YAML文件的扩展名为 .yml 或 .yaml ,它的基本要求如下:

1 大小写敏感

2 使用缩进代表层级关系

3 相同的部分只出现一次

比如使用properties文件配置tomcat端口:  server.port=8888

而使用YAML文件配置tomcat端口: 

server:
 port: 8888

YAML文件_自定义配置简单数据

 除了覆盖默认配置,我们还可以在YAML文件中配置其他信息以便我 们在项目中使用。配置简单数据的方式如下:

 语法:

       数据名: 值

示例代码:

      name: baizhan

注意:value之前有一个空格

 YAML文件_自定义配置对象数据

 对象:

      属性名1: 属性值

      属性名2: 属性值

# 或者

对象: {属性名1: 属性值,属性名2: 属性值}

 示例代码:

# 学生1
student1:
 sex: female
 age: 10
 address: beijing


# 学生2
student2: {sex: female,age: 10,address: beijing}

 属性名前面的空格个数不限,在yml语法中,相同缩进代表同一 个级别,只要每个属性前的空格数一样即可。

 YAML文件_自定义配置集合数据

 语法

集合:

       - 值1

       - 值2

# 或者

集合: [值1,值2]

 示例代码

# 城市
city1:
 - beijing
 - tianjin
 - shanghai
 - chongqing


city2:
[beijing,tianjin,shanghai,chongqing]


# 集合中的元素是对象
students:
 - name: xiaotong
   age: 18
   score: 100
 - name: shangxuetang
   age: 28
   score: 88
 - name: chengxuyuan
   age: 38
   score: 90

注意:值与之前的 - 之间存在一个空格

 

YAML文件_读取配置文件的数据

使用@Value读取

 我们可以通过@Value注解将配置文件中的值映射到一个Spring管理 的Bean的字段上,用法如下:

 配置文件

name: baizhan


student:
 sex: female
 age: 10
 address: beijing


city1:
 - beijing
 - tianjin
 - shanghai
 - chongqing

students:
 - name: xiaotong
   age: 18
   score: 100
 - name: shangxuetang
   age: 28
   score: 88
 - name: chengxuyuan
   age: 38
   score: 90

读取配置文件数据:

@Controller
public class YmlController1 {
    @Value("${name}")
    private String name;

    @Value("${student1.age}")
    private int age;

    @Value("${city1[0]}")
    private String city1;

    @Value("${students[0].score}")
    private double score1;

    @RequestMapping("/yml1")
    @ResponseBody
    public String yml1(){
        System.out.println(name);
        System.out.println(age);
        System.out.println(city1);
        System.out.println(score1);
        return "hello springboot!";
   }
}

@Value只能映射简单数据类型,不能将yaml文件中的对 象、集合映射到属性中。

 

使用@ConfigurationProperties读取

通过 @ConfigurationProperties(prefifix="对象") 可以将配置文件中的配置自动与实 体进行映射,这样可以将yml文件中配置的对象属性直接映射到 Bean当中。 

 配置文件

user:
 id: 10001
 username: shangxuetang
 address:
   - beijing
   - tianjin
   - shanghai
   - chongqing
 grades:
   - subject: math
     score: 100
   - subject: english
     score: 90

实体类

public class Grade {
    private String subject;
    private double score;
    // 省略getter/setter/tostring
}

读取配置文件

@Controller
@ConfigurationProperties(prefix = "user")
public class YmlController2 {
    private int id;
    private String username;
    private List<String> address;
    private List<Grade> grades;
    @RequestMapping("/yml2")
    @ResponseBody
    public String yml2(){
        System.out.println(id);
        System.out.println(username);
        System.out.println(address);
        System.out.println(grades);
        return "hello springboot!";
   }
    public int getId() {
        return id;
   }
    public void setId(int id) {
        this.id = id;
}
    public String getUsername() {
        return username;
   }
    public void setUsername(String username) {
        this.username = username;
   }
    public List<String> getAddress() {
        return address;
   }
    public void setAddress(List<String> address) {
        this.address = address;
   }
    public List<Grade> getGrades() {
        return grades;
   }
    public void setGrades(List<Grade> grades) {
        this.grades = grades;
   }
}

YAML文件_占位符的使用

 

 YAML文件中可以使用 ${} 占位符,它有两个作用:

 使用配置文件中的值

编写配置文件

server:
 port: 8888
myconfig:
 myport: ${server.port}

读取配置文件

@Controller
public class YmlController3 {
    @Value("${myconfig.myport}")
    private int port;
    @RequestMapping("/yml3")
    @ResponseBody
    public String yml3(){
        System.out.println(port);
        return "hello springboot!";
   }
}

使用框架提供的方法

SpringBoot框架提供了一些生成随机数的方法可以在yml文件中使 用:

 

 用法如下:

# 随机生成tomcat端口
server:
 port: ${random.int(1024,9999)}

YAML文件_配置文件存放位置及优先级

 配置文件有如下存放位置:

  1.  项目根目录下
  2.  项目根目录下的/config子目录中
  3.  项目的resources目录中
  4.  项目的resources下的/config子目录中

这些目录下都可以存放两类配置文件,分别是 application.yml 和 application.properties ,这些配置文件的优先级从高到低依次为:

 项目根目录下的/config子目录中

  •        config/application.properties
  •        config/application.yml

项目根目录下

  •       application.properties
  •       application.yml

项目的resources下的/config子目录中

  •      resources/config/application.properties
  •      resources/config/application.yml

项目的resources目录中

  •     resources/application.properties
  •     resources/application.yml

优先级高的文件会覆盖优先级低的文件中的配置

 

YAML文件_bootstrap配置文件

 SpringBoot中有两种容器对象,分别是bootstrap和application, bootstrap是应用程序的父容器,bootstrap加载优先于 applicaton。bootstrap配置文件主要对bootstrap容器进行配置, application配置文件是对applicaton容器进行配置。 bootstrap配置文件也同样支持properties和yml两种格式,主要用 于从外部引入Spring应用程序的配置。 bootstrap配置文件特征

  • boostrap由父ApplicationContext加载,比applicaton优先加载。
  • boostrap里面的属性不能被覆盖。

bootstrap与application的应用场景

  • application配置文件主要用于SpringBoot项目的自动化配 置。
  • bootstrap配置文件有以下几个应用场景。
  1. 使用Spring Cloud Config配置中心时,需要在bootstrap配置文件中添加连接到配置中 心的配置属性来加载外部配置中心的配置信息。
  2. 一些固定的不能被覆盖的属性。
  3. 一些加密/解密的场景。

SpringBoot注册web组件_注册Servlet 

 由于SpringBoot项目没有web.xml文件,所以无法在web.xml中注 册web组件,SpringBoot有自己的方式注册web组件。

 注册方式一

  • 编写servlet

@WebServlet("/first")
public class FirstServlet extends
HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response){
        System.out.println("First Servlet........");
   }
}
  • 启动类扫描web组件
@SpringBootApplication
//SpringBoot启动时扫描注册注解标注的Web组件
@ServletComponentScan
public class Springbootdemo2Application {
    public static void main(String[] args)
       {
      
          SpringApplication.run(Springbootdemo2Application.class, args);
   }
}

 注册方式二 

  • 编写servlet

public class SecondServlet extends
HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response){
        System.out.println("Second Servlet........");
   }
}
  • 使用配置类注册servlet

@Configuration
public class ServletConfig {
    //ServletRegistrationBean可以注册
      Servlet组件,将其放入Spring容器中即可注册Servlet
    @Bean
    public ServletRegistrationBean getServletRegistrationBean(){
        // 注册Servlet组件
        ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());
        // 添加Servlet组件访问路径
        bean.addUrlMappings("/second");
        return bean;
   }
}

 SpringBoot注册web组件_注册Filter

 注册方式一

  •  编写filter

@WebFilter(urlPatterns = "/first")
public class FirstFilter implements Filter
{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException { }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进入First Filter");
      
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("离开First Filter");
   }
    @Override
    public void destroy() { }
}
  • 启动类扫描web组件
@SpringBootApplication
//SpringBoot启动时扫描注册注解标注的Web组件
@ServletComponentScan
public class Springbootdemo2Application {
    public static void main(String[] args)
  {
      
      SpringApplication.run(Springbootdemo2Appl ication.class, args);
   }
}

 注册方式二

  • 编写filter

public class SecondFilter implements
Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException { }
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进入Second Filter");
      
    filterChain.doFilter(servletRequest,servletResponse);

    System.out.println("离开Second Filter");
   }
    @Override
    public void destroy() { }
}
  • 使用配置类注册filter

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean getFilterRegistrationBean(){
        // 注册filter组件
        FilterRegistrationBean bean =  new FilterRegistrationBean(new SecondFilter());
        // 添加过滤路径
        bean.addUrlPatterns("/second");
        return bean;
   }
}

SpringBoot注册web组件_注册Listener

 注册方式一 

  •        编写Listener
@WebListener
public class FirstListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("First ListenerInit......");
   }
    @Override
    public void contextDestroyed(ServletContextEvent sce){
   }
}

启动类扫描web组件

@SpringBootApplication
//SpringBoot启动时扫描注册注解标注的Web组件
@ServletComponentScan
public class Springbootdemo2Application {
    public static void main(String[] args){       
      SpringApplication.run(Springbootdemo2Appl ication.class, args);
   }
}

注册方式二

  •  编写Listener
public class SecondListener implements
ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("Second Listener Init......");
   }
    @Override
    public void contextDestroyed(ServletContextEvent sce){
   }
}

使用配置类注册Listener

@Configuration
public class ListenerConfig {
    @Bean
    public ServletListenerRegistrationBean getServletListenerRegistrationBean(){
        ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean(new SecondListener());
        return bean;
   }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/759256.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

react+unittest+flask 接口自动化测试平台

目录 1 前言 2 框架 2-1 框架简介 2-2 框架介绍 2-3 框架结构 3 平台 3-1 平台组件图 1 新建用例 2 生成测试任务 3 执行并查看测试报告 3-2 用例管理 3-2-1 用例设计 3-3 任务管理 3-3-1 创建任务 3-3-2 执行任务 3-3-3 测试报告 3-3-4 邮件通知 1 前言 在现…

【电路原理学习笔记】第3章:欧姆定律:3.4 电阻的计算

第3章&#xff1a;欧姆定律 3.4 电阻的计算 电阻相关欧姆定律公式&#xff1a; R V I R\frac{V}{I} RIV​ 【例3-16】在图3-13所示的电路中&#xff0c;电阻为多少时&#xff0c;电池的电流才为3.08A&#xff1f; 【答】 R V I 12 V 3.08 A 3.90 Ω R\frac{V}{I}\frac{1…

AI大模型的现状与发展

AI大模型的现状与发展 &#x1f607;博主简介&#xff1a;我是一名正在攻读研究生学位的人工智能专业学生&#xff0c;我可以为计算机、人工智能相关本科生和研究生提供排忧解惑的服务。如果您有任何问题或困惑&#xff0c;欢迎随时来交流哦&#xff01;&#x1f604; ✨座右铭…

leetcode 108. 将有序数组转换为二叉搜索树

2023.7.16 由数组构造二叉搜索树地问题&#xff0c;本题可以借鉴从中序与后序遍历序列构造二叉树 这道题&#xff0c;这类题本质就是寻找分割点&#xff0c;分割点作为当前节点&#xff0c;然后递归左区间和右区间。 下面直接看代码&#xff1a; class Solution { public:Tree…

电子器件系列43:贴片led、发光二极管

干货&#xff01;发光二极管的全面解读 二极管、发光二极管参数详解_sam-zy的博客-CSDN博客 对几个型号的贴片led进行参数解读&#xff1a; ols-330 特性&#xff1a; 带镜头&#xff0c;从PCB背面安装 视角40 贴片1206 尺寸&#xff1a;3.2(长)x1.6(宽)x1.9(高)mm …

明代元素时装小姐姐【InsCode Stable Diffusion美图活动一期】

一、 Stable Diffusion 模型在线使用地址&#xff1a;https://inscode.csdn.net/inscode/Stable-Diffusion 二、模型版本及相关配置&#xff1a; 模型&#xff1a;chilloutmix_NiPrunedFp32Fix Lora&#xff1a;hanfu_ming 采样迭代步数&#xff08;steps&#xff09;: 40 采样…

故障排错篇之OSPF协议

一、OSPF邻居建立不成功 1、从理论上判断问题的所在 1.1、检查邻居两端的接口物理和协议状态是否UP&#xff0c;状态是否稳定&#xff0c;接口是否有丢包&#xff0c;两边互ping大包是否能通 若物理接口不Up或是不稳定&#xff08;有振荡现象&#xff09;&#xff0c;请排查…

NodeJS 文件操作封装 ②①

文章目录 前言导入模块创建文件递归删除文件&文件夹下载写入图片根据URL路劲返回Base64图片链接根据URL路劲异步返回Base64图片链接封装代码暴露模块总结 ⡖⠒⠒⠒⠤⢄⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸ ⠀⠀⠀⡼⠀⠀⠀⠀ ⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢶⣲⡴⣗⣲⡦…

【java爬虫】使用selenium获取某宝联盟淘口令

上一篇文章我们已经介绍过使用selenium获取优惠券基本信息的方法 (15条消息) 【java爬虫】使用selenium爬取优惠券_haohulala的博客-CSDN博客 本文将在上一篇文章的基础上更进一步&#xff0c;获取每个优惠券的淘口令&#xff0c;毕竟我们只有复制淘口令才能在APP里面获取优惠…

Appium python 框架

目录 前言 流程 结构 具体说说 run.py 思路 其他模块 前言 Appium是一个开源的移动应用自动化测试框架&#xff0c;它允许开发人员使用多种编程语言&#xff08;包括Python&#xff09;来编写自动化测试脚本。Appium框架提供了一套API和工具&#xff0c;可以与移动设备进…

C语言——指针详解(初阶)

轻松学会C语言指针 前言&#xff1a;一、指针是什么&#xff1f;1.1 指针是什么&#xff1f;1.2 指针变量1.3 总结 二、指针和指针类型2.1指针-整数2.2 指针的解引用 三、野指针3.1野指针的成因3.2如何避免野指针 四、指针运算4.1 指针-整数4.2指针-指针4.3指针的关系运算 五、…

【学会动态规划】不同路径(5)

目录 动态规划怎么学&#xff1f; 1. 题目解析 2. 算法原理 1. 状态表示 2. 状态转移方程 3. 初始化 4. 填表顺序 5. 返回值 3. 代码编写 写在最后&#xff1a; 动态规划怎么学&#xff1f; 学习一个算法没有捷径&#xff0c;更何况是学习动态规划&#xff0c; 跟我…

Delete `␍`eslint(prettier/prettier)报错的终极解决方案

1.背景 在进行代码仓库clone打开后&#xff0c;vscode报错全屏的 Delete ␍eslint(prettier/prettier)问题 2. 解决方案&#xff1a; 1.vscode直接转化 好处&#xff1a;直接转化当前页面的报错 坏处&#xff1a;每个界面都需要来一遍 2.设置git配置 好处&#xff1a;一…

竞赛信息管理系统——SSM

目录 一、项目简介 二、前置配置 1、创建数据库 2、编写application.yml文件 三、公共基础类 1、自定义登录拦截器类 2、自定义拦截规则 3、统一数据返回类 4、统一异常处理类 5、工具类 a、密码工具类 b、时间工具类 6、全局变量 四、用户模块 1、定义…

echarts环形图两层

1、实现效果 环形图&#xff0c;有两层环形&#xff0c;扇形之间有间隔&#xff0c;中间是标题&#xff0c;图例是自定义图片 2、实现 在template里写一个盒子放图表 <div class"chartMachineStyle" ref"chartMachine"></div>在style里设置盒…

状态模式:游戏、工作流引擎中常用的状态机是如何实现的?

从今天起&#xff0c;我们开始学习状态模式。在实际的软件开发中&#xff0c;状态模式并不是很常用&#xff0c;但是在能够用到的场景里&#xff0c;它可以发挥很大的作用。从这一点上来看&#xff0c;它有点像我们之前讲到的组合模式。 可以简短的回顾一下组合模式&#xff1a…

Windows cmd窗口下的代码页

查看当前的活动代码页 在cmd窗口下执行命令chcp可以查看当前的活动代码页&#xff1a; 临时修改活动代码页 在cmd窗口下执行命令chcp [nnn]&#xff0c;可以临时修改活动代码页&#xff08;窗口关闭后修改就失效了&#xff09;&#xff0c;其中[nnn]表示具体的代码页标识符…

Java 中的反射是什么?如何使用它?

Java 中的反射是什么&#xff1f;如何使用它&#xff1f; 在 Java 编程中&#xff0c;反射是一种高级的编程技术&#xff0c;可以在运行时动态地获取和操作类的信息。反射使得程序可以在运行时对类进行检查和操作&#xff0c;而不需要在编译时知道类的完整信息。这使得程序可以…

flstudio怎么保存工程文件?详解FL Studio 21保存文件的方法

FL Studio 21全称Fruity Loops Studio2023&#xff0c;这款软件也被人们亲切的称之为水果&#xff0c;它是一款功能强大的音乐创作编辑软件&#xff0c;拥有全功能的录音室&#xff0c;大混音盘以及先进的音乐制作工具&#xff0c;用户通过使用该软件&#xff0c;就可以轻松制作…