SpringBoot快速入门

目录

SpringBoot概述

功能

自动配置

Spring Boot的自动配置是一个运行时(程序启动时)的过程,考虑了众多因素,才决定Spring配置应该用哪个,不该用哪个。该过程是SpringBoot自动完成的

起步依赖

起步依赖本质上是一个Maven项目对象模型,定义了对其他库的传递依赖,这些东西加在一起即支持某项功能。

起步依赖就是将具备某种功能的坐标打包到一起,并提供一些默认的功能

辅助功能

提供了一些大型项目中常见的非功能性的特性,如嵌入式服务器,安全,指标,健康检测,外部配置等

Spring Boot不是对Spring功能上的增强,而是提供了一种快速使用Spring的方式

搭建项目

  1. 创建Maven项目
  2. 导入Spring Boot起步依赖
java 复制代码
<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>4.1.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    <!--springboot工程需要继承的父工程,内部定义了各种依赖的指定版本-->
    </parent>
    <groupId>com.xiehetao</groupId>
    <artifactId>springboot-helloworld</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Boot_HelloWorld</name>
    <description>Boot_HelloWorld</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!--web开发的起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
  1. 定义Controller类
  2. 编写引导类
java 复制代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class BootHelloWorldApplication {
    //项目运行入口
    public static void main(String[] args) {
        SpringApplication.run(BootHelloWorldApplication.class, args);
    }

}
  1. 启动测试

起步依赖原理

spring-boot-starter-parent包里定义了各种依赖的默认版本号,将来导入依赖包时不需要指定依赖版本

spring-boot-starter-web 该包是web项目的启动依赖,包含了启动web项目所必须的依赖包

Maven工程集成parent,引入starter后,通过依赖传递,可以简单方便的获取需要的jar包,并且不会存在版本冲突问题

配置

分类

Spring Boot 是基于约定的,很多配置都有默认值,如果想使用自己的配置替换掉默认配置的话,可以使用application.properties或者application.yml进行配置

同一级目录下优先级为:properties>yml>yaml

yaml

基本语法:

  1. 大小写敏感
  2. 数值前必须有空格,作为分隔符
  3. 使用空格缩进表示层级关系,相同缩进表示同一级
yaml 复制代码
# 对象
person:
	name: zhangsan
# 行内写法
person: {name: zhangsan}
# 数组
address:
	- beijing
	- nanjing
# 数组行内写法
address: [beijing,shanghai ]
# 纯量:单个,不可再分的值
msg1: 'hello \n world' # 单引号忽略转义字符
msg2: "hello \n world" # 双引号识别转义字符
# 引用
name: lisi 
person:
  name: ${name} # 引用已定义的name=lisi

配置读取

java 复制代码
@RestController
public class HelloController {
    //方式一:@Value注解读取
    @Value("${test.name}")
    private String name;
    //方式二:注入Environment环境变量
    @Autowired
    private Environment env;

    @RequestMapping("/hello")
    public String sayHello(){
        System.out.println(name);
        System.out.println(env.getProperty("person.name"));
        return "Hello Spring Boot!";
    }
}
//方式三:@Component+@ConfigurationProperties注解
@Component
@ConfigurationProperties(prefix="app")
class AppProperties{
}
//或者 方式四 @ConfigurationProperties+@Confuguration+@EnableConfigurationProperties(AppProperties.class)
@ConfigurationProperties(prefix="app")
class AppProperties{
//属性
}
@Confuguration
@EnableConfigurationProperties(AppProperties.class)
class AppConfig{
//里面不需要任何内容
}

profile

软件开发时不同环境使用的配置参数可能不一样,通过profile功能可以指定特定环境下的配置文件

配置方式

多profile文件方式 提供多个profile文件,代表不同环境下的配置

  • application-dev.yaml 开发环境
  • application-test.yaml 测试环境
  • application-pro.yaml 生产环境
    yaml多文档方式
    yaml文件中使用---分隔不同配置
激活方式
  • 配置文件: 配置文件中配置 spring.profiles.active=dev
  • 虚拟机参数:VM options指定 -Dsprig.profiles.active=dev
  • 命令行参数:java -jar xxx.jar --spring.profiles.active=dev

整合其他框架

JUnit

  1. 引入spring-boot-starter-test依赖
  2. 编写测试类,添加相关注解@Runwith(SpringRunner.class),@SpringBootTest(class=启动类.class),这里如果测试目录与启动类目录相同或者是其子目录,则不用标注class属性
  3. 编写测试方法,添加@Test注解

Redis

  1. 引入spring-boot-starter-data-redis
  2. 配置redis服务器地址
  3. 注入RedisTemplate模板

MyBatis

  1. 引入mybatis起步依赖,添加MySQL驱动
  2. 编写DataSource和Mybatis相关配置
  3. 定义表和实体类
  4. 编写dao和mapper文件/纯注解开发

SpringBoot高级

Spring Boot原理分析

自动配置

Condition

@ConditionOnClass

通过判断注解中给定的类是否存在来确定是否加载当前bean

java 复制代码
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(ClassConfig.class)
public @interface ConditionOnClass {
    //定义字符串数组,保存类全限定名
    String[] value();
}


public class ClassConfig implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // 获取ConditionOnClass注解上的属性
        Map<String, Object> map = metadata.getAnnotationAttributes(ConditionOnClass.class.getName());
        String[] value = (String[]) map.get("value");
        boolean flag = true;
        try {
            for (String s : value) {
                Class<?> aClass = Class.forName(s);
            }
        }catch (ClassNotFoundException e){
            flag = false;
        }
        return flag;
    }
}

案例

SpringBoot的web环境中默认使用tomcat作为内置服务器,其实SpringBoot提供了四种内置服务器供我们选择

bash 复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
        </dependency>
@Enable*注解

SpringBoot提供了很多Enable开头的注解,这些注解都是用于动态启用某些功能的,而其底层原理是使用@Import注解导入配置类,实现Bean的动态加载

java 复制代码
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(UserConfig.class)//UserConfig类里加载了User
public @interface EnableUser{
}
@Import注解

通过以下四种方式导入的类都会生成bean注入到IOC容器中

java 复制代码
@SpringBootApplication
//@EnableUser
//方式一 直接导入普通Bean
//@Import(User.class)
//方式二 导入配置类,配置类加不加@Configuration都可以
//@Import(UserConfig.class)
//方式三 导入ImportSelector的实现类
//@Import(MyImportSelector.class)
//方式四 导入ImportBeanDefinitionRegistrar实现类
//@Import({MyImportBeanDefinitionRegistrar.class})
public class BootHelloWorldApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(BootHelloWorldApplication.class, args);
//        Object user = context.getBean("user");
//        System.out.println(user);
        Role bean = context.getBean(Role.class);
        System.out.println(bean);
    }

}
@EnableAutoConfiguration注解

@EnableAutoConfiguration注解内部使用了@Import(AutoConfigurationImportSelector.class)来加载配置类

配置文件位置:META-INF/spring.factories,该配置文件定义了大量的配置类,当SpringBoot应用启动时,会自动加载这些配置类,初始化Bean

并不是所有的Bean都会被初始化,在配置类中使用Condition来加载满足条件的Bean

自动配置实战

定义配置类和实体类

java 复制代码
@AutoConfiguration//springboot4.+版本
@EnableConfigurationProperties(RedisProperties.class)
public class RedisAutoConfiguration {

    @Bean
    public Jedis jedis(RedisProperties redisProperties){
        return new Jedis(redisProperties.getHost(),redisProperties.getPort());
    }
}
@ConfigurationProperties(prefix = "redis")
public class RedisProperties {

    private String host = "localhost";
    private int port = 6379;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}

创建配置文件

java 复制代码
//文件路径及名称 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
com.xiehetao.redis.configure.configuration.RedisAutoConfiguration

导入自动配置模块

java 复制代码
<dependency>
     <groupId>com.xiehetao</groupId>
     <artifactId>redis-spring-boot-autoconfigure</artifactId>
     <version>0.0.1-SNAPSHOT</version>
</dependency>

自动配置的过程是SpringBoot项目会读取各个模块下的META-INF目录下的自动配置类,然后将它放入到IOC容器中,这里利用的是@Import注解的功能三

SpringBoot监听机制

SpringBoot提供了四种监听接口

ApplicationRunner

java 复制代码
@Component
/*
    当项目启动时调用run方法,可以用来缓存预热
*/
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("ApplicationRunner...run");
        System.out.println(Arrays.asList(args.getSourceArgs()));
    }
}

CommandLineRunner

上面这两者是一样的

java 复制代码
@Component
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunner... run");
        System.out.println(Arrays.asList(args));
    }
}

ApplicationContextInitializer

java 复制代码
@Component
public class MyApplicationContextInitializer implements ApplicationContextInitializer {
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        System.out.println("MyApplicationContextInitializer...initializer");
    }
}

SpringApplicationRunListener

java 复制代码
@Component
public class MySpringApplicationRunListener implements SpringApplicationRunListener {
    @Override
    public void starting(ConfigurableBootstrapContext bootstrapContext) {
        System.out.println("starting...项目启动中");
    }

    @Override
    public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment) {
        System.out.println("environmentPrepared...环境准备完毕");
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        System.out.println("contextPrepared...上下文准备完毕");
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        System.out.println("contextLoaded...上下文加载完毕");
    }

    @Override
    public void started(ConfigurableApplicationContext context, @Nullable Duration timeTaken) {
        System.out.println("started...项目启动完毕");
    }

    @Override
    public void ready(ConfigurableApplicationContext context, @Nullable Duration timeTaken) {
        System.out.println("项目启动完毕,开始运行");
    }

    @Override
    public void failed(@Nullable ConfigurableApplicationContext context, Throwable exception) {
        System.out.println("项目启动失败...");
    }
}

SpringBoot流程分析

Spring Boot监控

SpringBoot自带监控功能Actuator,可以帮助实现对程序内部运行情况监控,比如监控状况,Bean加载情况,配置属性,日志信息等

使用

  1. 导入依赖坐标spring-boot-starter-actuator
  2. 访问http://localhost:8080/actuator
yaml 复制代码
management:
  endpoint:
    health:
      show-details: always # 显示详细信息
  endpoints:
    web:
      exposure:
        include: "*" # 显示web端的所有信息

SpringBoot Admin

包含Admin Server和Admin Client两个模块,可以将Actuator的信息以图形化的方式展现出来

服务器端

导入依赖包

java 复制代码
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
        </dependency>

开启admin服务

java 复制代码
@SpringBootApplication
@EnableAdminServer
public class SpringBootAdminServerApplication {

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

}

客户端

导入依赖包

java 复制代码
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-client</artifactId>
        </dependency>

添加配置

xml 复制代码
spring.boot.admin.client.url=http://localhost:9000
management.endpoint.health.show-details=always
management.endpoints.web.exposure.include=*

Spring Boot 项目部署

SpringBoot项目开发完毕后,支持两种方式部署到服务器:

  1. jar包(官方推荐,默认方式)
  2. war包

jar包

打包成jar包时,jar包内置了tomcat服务器,并且配置文件里的tomcat属性生效

war包

打包成war包,需要添加配置信息

java 复制代码
    <!--pom文件中指定打包方式-->
    <packaging>war</packaging>
java 复制代码
@SpringBootApplication
//继承SpringBootServletInitializer类,重写configure方法
public class SpringBootAdminServerApplication extends SpringBootServletInitializer {

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

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(SpringBootAdminServerApplication.class);
    }
}

并且运行的服务器上要有tomcat服务器,项目里的有关tomcat的配置无法生效

相关推荐
Zane19941 小时前
@property 到底是怎么把方法伪装成属性的?一文吃透 property、staticmethod、classmethod
后端·python
青山木2 小时前
Hot 100 --- 搜索插入位置
java·数据结构·算法·leetcode
Jul1en_2 小时前
【Claude Code Compact】源码级别的学习上下文压缩
java·前端·学习·github·ai编程
前端 贾公子2 小时前
第06章:结构化输出 (上)
java·服务器·前端
念何架构之路2 小时前
restartmanager-重启管理子系统
java·开发语言
用户8181870627463 小时前
第21章 JDBC 异常全集与连接池诊断
后端
Java内核笔记3 小时前
告别第三方库!Spring Boot 4 原生 API 版本控制全解析:4 种策略 + 实战案例
java·后端
神奇小汤圆3 小时前
把Spring Boot 4的Native Image玩明白了,启动3秒变50毫秒的踩坑全记录
后端
东方小月3 小时前
从零开发一个 Coding Agent(五):使用 TypeBox 校验工具参数
前端·人工智能·后端