springboot3 基础特性(1)

发布于:2024-06-19 ⋅ 阅读:(88) ⋅ 点赞:(0)

一、SpringApplication三种方式

1.1 基础方式


@SpringBootApplication
public class ShujufangwenApplication {

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

}

1.2.自定义 SpringApplication

在这里插入图片描述

在这里插入代码片@SpringBootApplication
public class ShujufangwenApplication {

    public static void main(String[] args) {


        SpringApplication springApplication=new SpringApplication(ShujufangwenApplication.class);
        //这种方式我们可以设置spring应用的一个配置
        //但是 配置文件中的优先级是要大于此种方式的
        springApplication.setBannerMode(Banner.Mode.OFF);
        springApplication.run(args);
    }

}

1.3、FluentBuilder API

也可以配置一些应用环境

@SpringBootApplication
public class ShujufangwenApplication {

    public static void main(String[] args) {


        new SpringApplicationBuilder().sources(ShujufangwenApplication.class)
                .bannerMode(Banner.Mode.CONSOLE)
                .run();
    }

}

二、自定义Banner

在这里插入图片描述
推荐网站:Spring Boot banner 在线生成工具,制作下载英文 banner.txt,修改替换 banner.txt 文字实现自定义,个性化启动 banner-bootschool.net

可以看到 spring启动时 图标变了
在这里插入图片描述

三、Profiles

3.1 什么是 Profiles ?

应用所在的运行环境发生切换时,配置文件常常就需要随之修改。

Profile:——就是一组配置文件及组件的集合。

可以整个应用在不同的profile之间切换(设置活动profile),整个应用都将使用该profile对应的配置文件及组件。

——每个运行环境(开发、测试、上线)都配置成一个对应profile,这样以后只要修改一下活动profile,应用就可以轻易地在不同的运行环境之间自由切换。

就是通过 配置的 profile 快速切换开发环境。

3.2 声明Profiles

我们可以用@Profile修饰Spring组件(@Component、@Configuration、@ConfigurationProperties),意味着该组件仅对特定profile有效。

在配置文件中添加profile名,意味着该配置文件仅对特定profile生效。

在这里插入图片描述

什么环境都不激活的话就是默认环境生效。
在这里插入图片描述

如果一个组件上什么都不标的话,就代表不管什么环境激活,都会生效,但如果标了default,就代表只有激活默认环境才会生效,需要注意
在这里插入图片描述

3.3 激活配置文件

命名:在 Spring Boot 中,Profile 是通过配置文件来实现的。在不同的环境下,可以加载不同的配置文件,从而实现不同的配置逻辑。具体来说,Spring Boot 支持以下几种配置文件:

application.properties
application.yml
application-{profile}.properties
application-{profile}.yml
其中,application.properties 和 application.yml 是通用的配置文件,它们在所有的环境下都会被加载。而 application-{profile}.properties 和 application-{profile}.yml 则是根据不同的 Profile 来加载的配置文件。当应用程序启动时,Spring Boot 会根据当前的环境变量来决定加载哪个配置文件。例如,如果当前环境变量为 dev,则会加载 application-dev.properties 或 application-dev.yml 文件。

在这里插入图片描述

如果激活环境与基础配置application.properties中的冲突的话,激活环境的优先。

3.3.1 分组

在这里插入图片描述
可以给激活环境分组 来直接激活该组。

3.3.2 环境包含

注意
1.spring.profiles.active 和spring.profiles.default 只能用到 无 profile 的文件中,如果在application-dev.yaml中编写就是无效的

环境包含就是:不论哪个环境生效,该环境都会包含进去生效。
在这里插入图片描述

3.3.3 激活方式

1、在配置文件中 使用spring.profiles.active=
2、通过命令行 --spring.profiles.active=dev,hsqldb

3.3.4 配置优先级

总结:
命令行>配置文件>Springapplication编程式配置
config子目录>config目录
config>根目录
{profile}>application
包外>包内
在这里插入图片描述