简述Spring Boot自动配置与yaml

Spring Boot自动配置与yaml

之前的博文主要简述了SpringBoot的几个特点,这里再补充一下

SpringBoot实现了自动配置(大多数用户平时习惯设置的配置作为默认配置)的功能来为用户快速构建出标准化的应用。

自动配置

pom.xml

SpingBoot与SSM不同,无需xml配置包和数据库连接池,那么它是如何实现的?首先是他的核心依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
  • SpringBoot最核心依赖parent
  • 在写或引入一些SpringBoot依赖时,无需指定版本,因为有版本仓库

启动器

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

启动器:SpringBoot的启动场景,包括自动配置,日志和yaml

	SpringBoot会将所有功能场景,变成一个个的启动器

例如:

  • spring-boot-starter-web,自动导入web环境所有依赖如tomcat、hibernate
  • spring-boot-starter-test 导入常规测试依赖,如JUnit、spring-test模块
  • spring-boot-starter-Redis 支持redis存储数据库,包括spring-redis

主程序

我们在创建一个Spring Boot的工程后,会发现src目录中有一个Application类,并且该类标注了@SpringBootApplication注解,该注解标注了这个类是一个Spring boot应用
点开@SpringBootApplication,其中有三个重要的注解

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)

@SpringBootConfiguration:只是个@Configuration注解的派生注解,只不过@Configuration用于spring标注配置类,@SpringBootConfiguration用于Spring Boot
@EnableAutoConfiguration:开启自动配置,自动导入借助SpringFactoriesLoader工具,将许多开源框架集合起来供使用
@@ComponentScan:自动扫描符合条件的组件并且装配到spring的bean容器中

yaml语言格式

SpringBoot有两种全局配置文件,配置文件名固定为application

  1. application.properties
  2. application.yaml(官方推荐)

例:端口配置,分别使用yaml、xml、和传统properties
yaml:

server:
  prot: 8080

xml:

<server>
	<port>8080<port>
</server>

properties:

server.port=8080

可以看出yaml的格式简单,结构更清晰,语法简介有严格缩进规则(空格)

发布了8 篇原创文章 · 获赞 3 · 访问量 380

猜你喜欢

转载自blog.csdn.net/weixin_43895548/article/details/104293844
今日推荐