SpringBoot学习笔记(一)——入门

本文是SpringBoot学习笔记的第一部分,主要介绍了SpringBoot的官方文档结构,入门步骤,包括优点和系统要求,自动配置的原理,以及开发小技巧。内容涵盖从创建Maven工程,编写主程序类,到配置文件的使用和自动配置的详解,还提到了简化部署和配置管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、SpringBoot官方文档架构

官方文档地址:https://docs.spring.io/spring-boot/docs/current/reference/html/
中文参考文档:http://felord.cn/_doc/_springboot/2.1.5.RELEASE/_book/pages/boot-documentation.html
在这里插入图片描述在这里插入图片描述查看SpringBoot版本更新内容:
https://spring.io/projects/spring-boot#overview

在这里插入图片描述

二、SpringBoot入门

1、SpringBoot优缺点

优点:

  • 创建独立的Spring应用
  • 内嵌web服务器
  • 自动starter依赖,简化构建配置
  • 自动配置Spring以及第三方功能
  • 提供生产级别的监控、健康检查及外部化配置
  • 无代码生成、无需编写XML

缺点:

  • 迭代更新速度快
  • 封装太深,内部原理复杂

2、系统要求

以下版本要求基于SpringBoot 2.6.4,其他参考官方文档

  • java 8 +
  • maven 3.5+

3、创建一个简单的应用程序

3.1、创建maven工程
 此处注意检查IDEA中maven的地址是否是自己的
在这里插入图片描述

3.2、引入依赖

  • 创建pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>myproject</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.4</version>
    </parent>

    <dependencies>
        #添加依赖
    </dependencies>

</project>
  • 添加相关依赖

#web场景依赖

    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

3.3、创建主程序类

MainApplication.java

@SpringBootApplication
public class MainApplication{

    public static void main(String[] args) {
        SpringApplication.run(BootWeb01Application.class, args);
    }
}

注解:@SpringBootApplication 标注在主程序类上,此类也是SpringBoot应用的启动类。
@SpringBootApplication 是一个合成注解:

@SpringBootConfiguration-->@Configuration  配置类
@EnableAutoConfiguration-->启用自动配置
@ComponentScan-->组件扫描器:默认扫描@ComponentScan所在包及子包中的类

3.4、编写业务代码

@RestController
public class HelloController {
    
    @RequestMapping("/hello")
    public String handle01(){ 
        return "hello,springboot 2";
    }
}

注解:@RestController =@Controller+@ResponseBody
@Controller:控制器类
@ResponseBody:标注在类上,表示该类所有方法的返回数据以字符串的方式写给浏览器

3.5、运行测试

 直接运行主程序类main方法即可

3.6、简化配置

 SpringBoot配置文件:application.properties 或 application.yml 。properties文件中的配置优先级高于yml文件中的。
官方文档配置项参考:https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html#appendix.application-properties

application.properties配置示例:

#配置端口号
server.port=8888

3.7、简化部署

 在pom.xml中修改打包方式,将程序打包成可执行的jar包。
pom.xml中添加:

#更改打包方式
<packaging>jar</packaging>

#引入SpringBoot提供的插件
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

使用maven打包程序
在这里插入图片描述在target目录找到jar包执行
在这里插入图片描述运行前取消cmd的快速编辑模式
在这里插入图片描述

注:如果打包失败,尝试修改maven插件版本

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <!--修改版本-->
    <version>3.1.0</version>
</plugin>

三、了解自动配置

1、springboot特点

1.1、依赖管理

  • 父项目做依赖管理
   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
它的父项目:
  <parent>
    <groupId>org.springframework.boot</groupId>
    #在此几乎声明了所有常用依赖的版本号,自动版本仲裁
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.6.3</version>
  </parent>
spring-boot-starter-aop             aop场景
spring-boot-starter-web             web场景

只要引入场景启动器,该场景所有 常规需要的依赖将自动引入。
官方启动器命名:spring-boot-starter-*
第三方启动器命名:*-spring-boot-starter

  • 自动版本仲裁
    引入非自动版本仲裁的依赖要写版本号。

  • 可以修改版本号
    在pom.xml中修改:

  <properties>
        <java.version>1.8</java.version>
        <mysql.version>5.1.43</mysql.version>
  </properties>

1、查看<artifactId>spring-boot-dependencies</artifactId>中规定当前依赖版本用的key
2、在pom.xml中重写配置

1.2、自动配置

  • 自动配好Tomcat
    (1)引入依赖
spring-boot-starter-web:
   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
      <version>2.6.3</version>
      <scope>compile</scope>
    </dependency>

  (2)自动配置

  • 自动配好SpringMVC
  • 自动配好web常用功能,如:字符编码问题、文件上传,视图解析器…
  • 默认的包结构
    主程序所在的包及其子包内的所有组件都能被扫描到。
    在这里插入图片描述

修改包扫描层级:

设置@SpringBootApplication注解的scanBasePackage属性、或者使用@ComponentScan注解

@SpringBootApplication(scanBasePackages = "com.bian")
public class BootWeb01Application {
}
@SpringBootApplication=@SpringBootConfiguration+@EnableAutoConfiguration+@ComponentScan
  • 各种配置都有默认配置
    默认配置最终都会映射到Multipartproperties,配置文件的值最终会绑定到相关类上并注册到容器中。
  • 按需加载所有自动配置项*
    SpringBoot所有的自动配置功能都在spring.boot.autoconfigure包下,引入了哪些场景,哪些场景的配置才会开启。

查看IoC容器中的所有组件:

public static void main(String[] args) {
        ConfigurableApplicationContext IoC = SpringApplication.run(BootWeb01Application.class, args);
        String[] names = IoC.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }
    }

2、容器功能

2.1、组件添加

① @Configuration

  • 基本使用
    标注在类上,表示该类是一个配置类。
@Configuration
public class MyConfig {

    @Bean
    public User user01(){
        return new User("zhang",18);
    }
    
    * @Bean注解 标注在方法上,给容器中添加组件
    * 返回类型为组件类型
    * 方法名为组件id,可以自定义:@Bean("tom")
    * 返回值为组件在容器中的实例 
}
  • Full模式与Lite模式
    示例:
@Configuration(proxyBeanMethods = true)
public class MyConfig {

    @Bean
    public User user01(){
        User user = new User("zhang", 18);
        /*User组件依赖了Pet组件*/
        user.setPet(tomPet());        
        return user;
    }
 
    @Bean("tom")
    public Pet tomPet(){
        return new Pet("tomcat");
    }
}

proxyBeanMethods:代理类的方法,默认为true
proxyBeanMethods = true:代理对象调用方法,每次调用总会检查组件是否已存在,确保组件单实例
proxyBeanMethods = false:对象本身调用方法,每次调用得到新的对象实例
  最佳实战:
 配置类组之间无依赖关系使用Lite模式,加速容器启动过程,减少判断。
 配置类组件之间有依赖关系,方法被调用得到的是已经存在的单实例组件,使用Full模式。

② @Bean、@Component、@Controller、@Service、@Repository

 SpringMVC模式向容器中注册组件

③ @ComponentScan、@import

 @ComponentScan:配置包扫描
 @import:向容器中导入组件

@Import({User.class,Pet.class})
@Configuration(proxyBeanMethods = true)
public class MyConfig {
}

④@Conditional

条件装配:可标注在类上和方法上,满足Contional指定的条件,才能使配置类生效或进行组件注入
在这里插入图片描述示例:
当容器中有名字为“tom”的组件才注入user01组件:

@Configuration
public class MyConfig {

    @ConditionalOnBean(name="tom")
    @Bean
    public User user01(){
        User user = new User("zhang", 18);
        /*User组件依赖了Pet组件*/
        user.setPet(tomPet());
        return user;
    }

    //@Bean("tom")
    public Pet tomPet(){
        return new Pet("tomcat");
    }
}

2.2、原生配置文件引入

1、@ImportResource
标注在配置类上,向容器中导入原生配置文件中定义的组件。

@Configuration
@ImportResource("classpath:beans.xml")
public class MyConfig {
}

2.3、配置绑定
使用注解将application.properties文件中的内容封装到JavaBean中,不能用于其他properties文件。

1、@EnableConfigurationProperties+@ConfigurationProperties
@EnableConfigurationProperties 标注在配置类上,会自动将该组件注册到容器中。常用于为第三方包中的类进行配置绑定。

@EnableConfigurationProperties(car.class)
@Configuration
public class MyConfig{
}
@ConfigurationProperties(prefix = "mycar")
public class Car {
}

2、@Component+@ConfigurationProperties
application.properties:

mycar.brand=BYD
mycar.price=10000

JavaBean:
标注在JavaBean上,只有容器中的JavaBean才能使用此功能。

@ConfigurationProperties(prefix = "mycar")
@Component
public class Car {

    private String brand;
    private Integer price;

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

2.4、修改默认配置

SpringBoot以用户配置优先原则,默认在底层配置好所有组件。
修改默认配置:
方法1.自定义组件进行替换

    @Bean
	public CharacterEncodingFilter characterEncodingFilter() {
	//创建对象
	//添加规则
	return xxx;
  }

方法2.修改配置文件application.properties
①查看官网可以修改那些配置。
②在org.springframework.boot.autoconfigure包中找到xxxAutoConfiguration.java,再找到该类的注解@EnableConfigurationProperties(xxx.class),在xxx.class中找到注解@ConfigurationProperties(prefix = “xxx,xxx”)中查看绑定的前缀,然后在配置文件中以此前缀修改配置。
底层给容器中重命名自定义的文件上传解析器;

        @Bean
		@ConditionalOnBean(MultipartResolver.class)  //容器中有这个类型组件
		@ConditionalOnMissingBean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME) //容器中没有这个名字 multipartResolver 的组件
		public MultipartResolver multipartResolver(MultipartResolver resolver) {
            //给@Bean标注的方法传入了对象参数,这个参数的值就会从容器中找。
            //SpringMVC multipartResolver。防止有些用户配置的文件上传解析器命名不符合规范
			return resolver;
		} 

查看SpringBoot开启了哪些配置
在application.properties中开启debug模式:debug=true
控制台中:Negative(不生效的)、Positive(生效的)

2.5、CommandLineRunner接口
开发中可能存在这样的场景:需要在容器启动后执行一些内容,比如读取配置文件,数据库连接之类的。SpringBoot提供了两个接口来实现这种需求:CommandLineRunner和ApplicationRunner
这两个接口中有一个run方法,只需要实现这个run方法就行。
两个接口的区别:ApplicationRunner中run方法的参数是ApplicationArguments,而CommandLineRunner中run方法的参数是String数组。

@SpringBootApplication
public class Boot02Application implements CommandLineRunner {

    public static void main(String[] args) {
        //第一步执行
        System.out.println("准备创建容器");
        //第二步执行
        SpringApplication.run(Boot02Application.class, args);
        //第四步执行
        System.out.println("容器创建后");
    }
		//第三步执行
    @Override
    public void run(String... args) throws Exception {
    //可以使用容器中的组件,包括自定义加入的组件
        System.out.println("容器对象创建好后,执行方法");
    }
}

四、开发小技巧

4.1、Lombok
简化JavaBean开发,自动生成getter、setter方法等…
①引入依赖

       <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

②给idea中安装lombok插件
③在JavaBean上标注相关注解

@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class Car {

    private String brand;
    private Integer price;
}
########################################
@RestController
@Slf4j
public class HelloController {

    @RequestMapping("/hello")
    public String handle01(){
        log.info("请求进来了...");
        return "hello,springboot 2";
    }
}

@Data :生成getter、setter方法
@ToString:生成toString方法
@AllArgsConstructor:生成全参构造器
@NoArgsConstructor:无参构造器
@EqualsAndHashCode:生成equals和hashCode方法
@Slf4j :注入日志类
4.2、Spring Initailizer
SpringBoot工程初始化向导,对需要的开发工具和场景启动器,SpringBoot版本等进行勾选,自动生成相关代码
在这里插入图片描述

4.3、dev-tools
自动重启,更新资源
①引入依赖

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

②修改代码后,按下ctrl+F9,或点击工具栏Build中的“Build Project”

4.4、processor
配置提示功能。自定义的类和配置文件绑定一般没有提示。

  <!--自定义类绑定配置文件提示-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

五、配置文件

1、文件类型
1.1、properties
application.properties,可以修改程序中的默认配置等

#配置tomcat端口号
server.port=8080
#配置访问应用上下文路径
server.servlet.context-path=/myboot

在IDEA中修改配置时properties文件支持中文:
在这里插入图片描述

1.2、yaml
yml文件非常适合用来做以数据为中心的配置文件

1.2.1、基本语法

  • key: value,k、v之间要有空格
  • 大小写敏感
  • 使用缩进表示层级关系
  • 缩进不允许使用tab键,只能使用空格
  • 缩进的空格个数不重要,只要相同层级的元素左对齐就行
  • 用‘#’表示注释
  • 使用‘’表示的字符会被转义,使用“”表示的字符不会转义
    例如:“张三 \n 李四”中的\n表示换行。‘张三 \n 李四’中的\n就是\n
  • 字符串可以直接写,不用加引号

1.2.2、数据类型

  • 字面量:date、boolean、string、number、null
k: v
  • 对象:map、hash、object
行内写法:k: {k1: v1,k2: v2,k3: v3}
或:
k: 
  k1: v1
  k2: v2
  k3: v3
  • 数组:array、list、set、queue
行内写法:k: [v1,v2,v3]
或
k:
 - v1
 - v2
 - v3

示例:

@ConfigurationProperties(prefix=“person”)
@Component
@Data
public class Person {
	
	private String userName;
	private Boolean boss;
	private Date birth;
	private Integer age;
	private Pet pet;
	private String[] interests;
	private List<String> animal;
	private Map<String, Object> score;
	private Set<Double> salarys;
	private Map<String, List<Pet>> allPets;
}

@Data
public class Pet {
	private String name;
	private Double weight;
}
# yaml表示以上对象
person:
  userName: zhangsan
  boss: false
  birth: 2019/12/12 20:12:33
  age: 18
  pet: 
    name: tomcat
    weight: 23.4
  interests: [篮球,游泳]
  animal: 
    - jerry
    - mario
  score:
    english: 
      first: 30
      second: 40
      third: 50
    math: [131,140,148]
    chinese: {first: 128,second: 136}
  salarys: [3999,4999.98,5999.99]
  allPets:
    sick:
      - {name: tom}
      - {name: jerry,weight: 47}
    health: [{name: mario,weight: 47}]

1.3、多环境配置
在实际开发中,会有开发环境、测试环境、上线环境等,每个环境都有不同的配置信息,比如端口、上下文、数据库配置信息等。为了方便切换不同的环境配置,可以使用多环境配置。
使用方式:
1、创建多个配置文件,名称规则:application-环境名称.properties(yml)
例如:

开发环境:application-dev.properties
测试环境:application-test.properties
上线环境:application-online.properties

2、在主配置文件中激活使用哪个配置文件
application.properties:

#激活使用哪个配置文件
#启动测试环境的配置文件
spring.profiles.active=test

1.4、使用@Value注解获取配置文件中的值
对于自定义类,可以使用@ConfigurtionProperties注解与配置文件绑定
application.properties

server.port=8080
person.name=张三

controller:

@RestController
public class HelloController {

    @Value("${server.port}")
    private Integer port;

    @Value("${person.name}")
    private String name;

    @RequestMapping("/hello")
    public String queryData(){
        return name+port;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值