文章目录
- 1 依赖方式
- 1.1 spring-boot-starter-parent依赖
- 1.2 spring-boot-dependencies依赖
- 1.3 对比
- 2 使用方式
- 2.1 @SpringbootApplication
- 2.2 高度定制
- 3 springboot各种配置优先级顺序
- 4 sprinboot配置文件解析顺序
- 结语
1 依赖方式
这里项目以开源的renren和pig为例,我们来看看两种依赖方式的引入。
1.1 spring-boot-starter-parent依赖
renren-security项目中pom.xml文件引入依赖如下所示:
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>io.renren</groupId><artifactId>renren-security</artifactId><version>5.2.0</version><packaging>pom</packaging><name>renren-security</name><description>人人权限系统</description><url>https://www.renren.io</url><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.5</version></parent><modules><module>renren-common</module><module>renren-dynamic-datasource</module><module>renren-admin</module><module>renren-api</module><module>renren-generator</module></modules><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version><jedis.version>4.2.2</jedis.version><druid.version>1.2.13</druid.version><mybatisplus.version>3.5.2</mybatisplus.version><sqlserver.version>4.0</sqlserver.version><oracle.version>11.2.0.3</oracle.version><dameng.version>8.1.2.79</dameng.version><commons.lang.version>3.12.0</commons.lang.version><commons.fileupload.version>1.4</commons.fileupload.version><commons.io.version>2.11.0</commons.io.version><commons.codec.version>1.15</commons.codec.version><guava.version>20.0</guava.version><joda.time.version>2.10.14</joda.time.version><hutool.version>5.7.22</hutool.version><gson.version>2.9.0</gson.version><jsoup.version>1.15.3</jsoup.version><knife4j.version>2.0.9</knife4j.version><lombok.version>1.18.24</lombok.version><docker.plugin.version>1.1.1</docker.plugin.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>${jedis.version}</version></dependency><!-- mysql驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!-- oracle驱动 --><dependency><groupId>com.oracle</groupId><artifactId>ojdbc6</artifactId><version>${oracle.version}</version></dependency><!-- sqlserver驱动 --><dependency><groupId>com.microsoft.sqlserver</groupId><artifactId>sqljdbc4</artifactId><version>${sqlserver.version}</version></dependency><!-- postgresql驱动 --><dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId></dependency><!-- 达梦驱动 --><dependency><groupId>com.dameng</groupId><artifactId>DmJdbcDriver18</artifactId><version>${dameng.version}</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>${druid.version}</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>${mybatisplus.version}</version><exclusions><exclusion><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>${commons.lang.version}</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>${commons.fileupload.version}</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>${commons.io.version}</version></dependency><dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId><version>${commons.codec.version}</version></dependency><dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>${guava.version}</version></dependency><dependency><groupId>joda-time</groupId><artifactId>joda-time</artifactId><version>${joda.time.version}</version></dependency><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>${gson.version}</version></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>${hutool.version}</version></dependency><dependency><groupId>org.jsoup</groupId><artifactId>jsoup</artifactId><version>${jsoup.version}</version></dependency><dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-boot-starter</artifactId><version>${knife4j.version}</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>${lombok.version}</version></dependency></dependencies><!-- 阿里云maven仓库 --><repositories><repository><id>public</id><name>aliyun nexus</name><url>https://maven.aliyun.com/repository/public/</url><releases><enabled>true</enabled></releases></repository></repositories><pluginRepositories><pluginRepository><id>public</id><name>aliyun nexus</name><url>https://maven.aliyun.com/repository/public/</url><releases><enabled>true</enabled></releases><snapshots><enabled>false</enabled></snapshots></pluginRepository></pluginRepositories>
</project>
我们在spring-boot-parent jar包中,并没有具体的java代码,主要就是pom.xml文件,内容如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><!-- This module was also published with a richer model, Gradle metadata, --><!-- which should be used instead. Do not delete the following line which --><!-- is to indicate to Gradle or any Gradle module metadata file consumer --><!-- that they should prefer consuming it instead. --><!-- do_not_remove: published-with-gradle-metadata --><modelVersion>4.0.0</modelVersion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-parent</artifactId><version>2.7.5</version><packaging>pom</packaging><name>spring-boot-parent</name><description>Spring Boot Parent</description><url>https://spring.io/projects/spring-boot</url><organization><name>Pivotal Software, Inc.</name><url>https://spring.io</url></organization><licenses><license><name>Apache License, Version 2.0</name><url>https://www.apache.org/licenses/LICENSE-2.0</url></license></licenses><developers><developer><name>Pivotal</name><email>info@pivotal.io</email><organization>Pivotal Software, Inc.</organization><organizationUrl>https://www.spring.io</organizationUrl></developer></developers><scm><connection>scm:git:git://github.com/spring-projects/spring-boot.git</connection><developerConnection>scm:git:ssh://git@github.com/spring-projects/spring-boot.git</developerConnection><url>https://github.com/spring-projects/spring-boot</url></scm><issueManagement><system>GitHub</system><url>https://github.com/spring-projects/spring-boot/issues</url></issueManagement><properties><android-json.version>0.0.20131108.vaadin1</android-json.version><api-guardian.version>1.1.0</api-guardian.version><c3p0.version>0.9.5.5</c3p0.version><commons-compress.version>1.21</commons-compress.version><commons-fileupload.version>1.4</commons-fileupload.version><jakarta-inject.version>1.0.5</jakarta-inject.version><jline.version>2.11</jline.version><jna.version>5.7.0</jna.version><jopt-simple.version>5.0.4</jopt-simple.version><maven.version>3.6.3</maven.version><maven-common-artifact-filters.version>3.2.0</maven-common-artifact-filters.version><maven-invoker.version>3.1.0</maven-invoker.version><maven-plugin-tools.version>3.6.0</maven-plugin-tools.version><maven-resolver.version>1.6.3</maven-resolver.version><maven-shade-plugin.version>3.2.4</maven-shade-plugin.version><mockk.version>1.10.6</mockk.version><plexus-build-api.version>0.0.7</plexus-build-api.version><plexus-sec-dispatcher.version>1.4</plexus-sec-dispatcher.version><simple-jndi.version>0.23.0</simple-jndi.version><sisu.version>2.6.0</sisu.version><snakeyaml.version>1.32</snakeyaml.version><spock-framework.version>2.0-groovy-3.0</spock-framework.version><testng.version>6.14.3</testng.version><spring-asciidoctor-extensions.version>0.6.0</spring-asciidoctor-extensions.version><testcontainers.version>1.17.3</testcontainers.version></properties><dependencyManagement><dependencies><dependency><groupId>com.vaadin.external.google</groupId><artifactId>android-json</artifactId><version>${android-json.version}</version></dependency><dependency><groupId>org.apiguardian</groupId><artifactId>apiguardian-api</artifactId><version>${api-guardian.version}</version></dependency><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>${c3p0.version}</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-compress</artifactId><version>${commons-compress.version}</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>${commons-fileupload.version}</version></dependency><dependency><groupId>jakarta.inject</groupId><artifactId>jakarta.inject-api</artifactId><version>${jakarta-inject.version}</version></dependency><dependency><groupId>jline</groupId><artifactId>jline</artifactId><version>${jline.version}</version></dependency><dependency><groupId>net.java.dev.jna</groupId><artifactId>jna-platform</artifactId><version>${jna.version}</version></dependency><dependency><groupId>net.sf.jopt-simple</groupId><artifactId>jopt-simple</artifactId><version>${jopt-simple.version}</version></dependency><dependency><groupId>org.apache.maven</groupId><artifactId>maven-plugin-api</artifactId><version>${maven.version}</version></dependency><dependency><groupId>org.apache.maven</groupId><artifactId>maven-resolver-provider</artifactId><version>${maven.version}</version></dependency><dependency><groupId>org.apache.maven</groupId><artifactId>maven-settings-builder</artifactId><version>${maven.version}</version></dependency><dependency><groupId>org.apache.maven.shared</groupId><artifactId>maven-common-artifact-filters</artifactId><version>${maven-common-artifact-filters.version}</version></dependency><dependency><groupId>org.apache.maven.shared</groupId><artifactId>maven-invoker</artifactId><version>${maven-invoker.version}</version></dependency><dependency><groupId>org.apache.maven.plugin-tools</groupId><artifactId>maven-plugin-annotations</artifactId><version>${maven-plugin-tools.version}</version></dependency><dependency><groupId>org.apache.maven.resolver</groupId><artifactId>maven-resolver-api</artifactId><version>${maven-resolver.version}</version></dependency><dependency><groupId>org.apache.maven.resolver</groupId><artifactId>maven-resolver-connector-basic</artifactId><version>${maven-resolver.version}</version></dependency><dependency><groupId>org.apache.maven.resolver</groupId><artifactId>maven-resolver-impl</artifactId><version>${maven-resolver.version}</version></dependency><dependency><groupId>org.apache.maven.resolver</groupId><artifactId>maven-resolver-spi</artifactId><version>${maven-resolver.version}</version></dependency><dependency><groupId>org.apache.maven.resolver</groupId><artifactId>maven-resolver-transport-file</artifactId><version>${maven-resolver.version}</version></dependency><dependency><groupId>org.apache.maven.resolver</groupId><artifactId>maven-resolver-transport-http</artifactId><version>${maven-resolver.version}</version></dependency><dependency><groupId>org.apache.maven.resolver</groupId><artifactId>maven-resolver-util</artifactId><version>${maven-resolver.version}</version></dependency><dependency><groupId>org.apache.maven.plugins</groupId><artifactId>maven-shade-plugin</artifactId><version>${maven-shade-plugin.version}</version></dependency><dependency><groupId>io.mockk</groupId><artifactId>mockk</artifactId><version>${mockk.version}</version></dependency><dependency><groupId>org.sonatype.plexus</groupId><artifactId>plexus-build-api</artifactId><version>${plexus-build-api.version}</version></dependency><dependency><groupId>org.sonatype.plexus</groupId><artifactId>plexus-sec-dispatcher</artifactId><version>${plexus-sec-dispatcher.version}</version></dependency><dependency><groupId>com.github.h-thurow</groupId><artifactId>simple-jndi</artifactId><version>${simple-jndi.version}</version></dependency><dependency><groupId>org.sonatype.sisu</groupId><artifactId>sisu-inject-plexus</artifactId><version>${sisu.version}</version></dependency><dependency><groupId>org.yaml</groupId><artifactId>snakeyaml</artifactId><version>${snakeyaml.version}</version></dependency><dependency><groupId>org.spockframework</groupId><artifactId>spock-core</artifactId><version>${spock-framework.version}</version></dependency><dependency><groupId>org.spockframework</groupId><artifactId>spock-spring</artifactId><version>${spock-framework.version}</version></dependency><dependency><groupId>org.testng</groupId><artifactId>testng</artifactId><version>${testng.version}</version></dependency><dependency><groupId>io.spring.asciidoctor</groupId><artifactId>spring-asciidoctor-extensions-spring-boot</artifactId><version>${spring-asciidoctor-extensions.version}</version></dependency><dependency><groupId>io.spring.asciidoctor</groupId><artifactId>spring-asciidoctor-extensions-section-ids</artifactId><version>${spring-asciidoctor-extensions.version}</version></dependency><dependency><groupId>org.testcontainers</groupId><artifactId>testcontainers-bom</artifactId><version>${testcontainers.version}</version><type>pom</type><scope>import</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>2.7.5</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><pluginManagement><plugins/></pluginManagement></build>
</project>
- 其中它也引用了spring-boot-dependencies依赖
1.2 spring-boot-dependencies依赖
pig中pom.xml引入依赖如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.pig4cloud</groupId><artifactId>pig</artifactId><name>${project.artifactId}</name><version>3.6.7</version><packaging>pom</packaging><url>https://www.pig4cloud.com</url><properties><spring-boot.version>2.7.10</spring-boot.version><spring-cloud.version>2021.0.6</spring-cloud.version><spring-cloud-alibaba.version>2021.0.5.0</spring-cloud-alibaba.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target><spring-boot-admin.version>2.7.10</spring-boot-admin.version><spring.authorization.version>0.4.1</spring.authorization.version><dynamic-ds.version>3.6.0</dynamic-ds.version><captcha.version>2.2.2</captcha.version><velocity.version>2.3</velocity.version><velocity.tool.version>3.1</velocity.tool.version><configuration.version>1.10</configuration.version><jasypt.version>3.0.5</jasypt.version><swagger.fox.version>3.0.0</swagger.fox.version><knife4j.ui.version>3.0.3</knife4j.ui.version><xxl-job.version>2.4.0</xxl-job.version><docker.plugin.version>0.32.0</docker.plugin.version><docker.host>http://192.168.0.100:2375</docker.host><docker.registry>192.168.0.100</docker.registry><docker.namespace>pig4cloud</docker.namespace><docker.username>username</docker.username><docker.password>password</docker.password><git.commit.plugin>4.9.9</git.commit.plugin><spring.checkstyle.plugin>0.0.38</spring.checkstyle.plugin></properties><!-- 以下依赖 全局所有的模块都会引入 --><dependencies><!--配置文件处理器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><!--配置文件加解密--><dependency><groupId>com.github.ulisesbocchio</groupId><artifactId>jasypt-spring-boot-starter</artifactId><version>${jasypt.version}</version></dependency><!--监控--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><!--监控客户端--><dependency><groupId>de.codecentric</groupId><artifactId>spring-boot-admin-starter-client</artifactId><version>${spring-boot-admin.version}</version></dependency><!--Lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>provided</scope></dependency><!--测试依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><modules><module>pig-register</module><module>pig-gateway</module><module>pig-auth</module><module>pig-upms</module><module>pig-common</module><module>pig-visual</module></modules><dependencyManagement><dependencies><!--pig 公共版本定义--><dependency><groupId>com.pig4cloud</groupId><artifactId>pig-common-bom</artifactId><version>${project.version}</version><type>pom</type><scope>import</scope></dependency><!-- spring boot 依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency><!-- spring cloud 依赖 --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>${spring-cloud.version}</version><type>pom</type><scope>import</scope></dependency><!-- spring cloud alibaba 依赖 --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-dependencies</artifactId><version>${spring-cloud-alibaba.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><finalName>${project.name}</finalName><resources><resource><directory>src/main/resources</directory><filtering>true</filtering></resource></resources><pluginManagement><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>${spring-boot.version}</version><configuration><finalName>${project.build.finalName}</finalName><layers><enabled>true</enabled></layers></configuration></plugin><plugin><groupId>io.fabric8</groupId><artifactId>docker-maven-plugin</artifactId><version>${docker.plugin.version}</version><configuration><!-- Docker Remote Api--><dockerHost>${docker.host}</dockerHost><!-- Docker 镜像私服--><registry>${docker.registry}</registry><!-- 认证信息--><authConfig><push><username>${docker.username}</username><password>${docker.password}</password></push></authConfig><images><image><!-- 镜像名称: 172.17.0.111/library/pig-gateway:2.6.3--><name>${docker.registry}/${docker.namespace}/${project.name}:${project.version}</name><build><dockerFile>${project.basedir}/Dockerfile</dockerFile></build></image></images></configuration></plugin></plugins></pluginManagement><plugins><!--打包jar 与git commit 关联插件--><plugin><groupId>io.github.git-commit-id</groupId><artifactId>git-commit-id-maven-plugin</artifactId><version>${git.commit.plugin}</version><executions><execution><id>get-the-git-infos</id><goals><goal>revision</goal></goals><phase>initialize</phase></execution></executions><configuration><failOnNoGitDirectory>false</failOnNoGitDirectory><generateGitPropertiesFile>true</generateGitPropertiesFile><!--因为项目定制了jackson的日期时间序列化/反序列化格式,因此这里要进行配置,不然通过management.info.git.mode=full进行完整git信息监控时会存在问题--><dateFormat>yyyy-MM-dd HH:mm:ss</dateFormat><includeOnlyProperties><includeOnlyProperty>^git.build.(time|version)$</includeOnlyProperty><includeOnlyProperty>^git.commit.(id|message|time).*$</includeOnlyProperty></includeOnlyProperties></configuration></plugin><!--代码格式插件,默认使用spring 规则,可运行命令进行项目格式化:./mvnw spring-javaformat:apply 或 mvn spring-javaformat:apply,可在IDEA中安装插件以下插件进行自动格式化:https://repo1.maven.org/maven2/io/spring/javaformat/spring-javaformat-intellij-idea-plugin--><plugin><groupId>io.spring.javaformat</groupId><artifactId>spring-javaformat-maven-plugin</artifactId><version>${spring.checkstyle.plugin}</version></plugin></plugins></build><profiles><profile><id>dev</id><properties><!-- 环境标识,需要与配置文件的名称相对应 --><profiles.active>dev</profiles.active><nacos.username>nacos</nacos.username><nacos.password>nacos</nacos.password></properties><activation><!-- 默认环境 --><activeByDefault>true</activeByDefault></activation></profile></profiles>
</project>
1.3 对比
spring-boot-dependencies
和spring-boot-starter-parent
都是用于管理Spring Boot项目的依赖项的工具,但它们之间有一些区别:
- BOM vs Parent POM(父项目):
spring-boot-dependencies
是一个Maven BOM(Bill of Materials),而spring-boot-starter-parent
是一个Maven父项目(Parent POM)。BOM用于集中管理依赖项的版本,而父项目除了管理依赖项的版本外,还可以提供一些默认配置和插件。 - 继承方式:使用
spring-boot-dependencies
时,你需要在项目的pom.xml
文件中显式地引用该BOM,通过<dependencyManagement>
部分进行引用。而使用spring-boot-starter-parent
时,你将项目的pom.xml
文件的<parent>
部分指向spring-boot-starter-parent
。 - 版本控制:
spring-boot-dependencies
主要用于集中管理Spring Boot及其相关依赖项的版本。它定义了一个确定的版本集,可以确保这些依赖项的版本兼容性。而spring-boot-starter-parent
不仅提供了版本管理功能,还提供了一些默认配置和插件,使你可以更轻松地启动和构建Spring Boot项目。 - 灵活性:使用
spring-boot-dependencies
可以与任何父项目一起使用,你可以选择任何适合你项目的父项目。而spring-boot-starter-parent
作为专门为Spring Boot设计的父项目,提供了一些默认配置和插件,使得配置更加简单,但可能会限制你对项目的灵活性。
总体而言,spring-boot-dependencies
用于集中管理依赖项的版本,而spring-boot-starter-parent
不仅提供了版本管理,还提供了一些默认配置和插件,使得构建和配置Spring Boot项目更加方便。你可以根据自己的需求和偏好选择使用哪种方式。
2 使用方式
这里的使用方式是指标注spirngboot应用的注解。
2.1 @SpringbootApplication
查看下注解源代码:
package org.springframework.boot.autoconfigure;import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.annotation.AliasFor;
import org.springframework.data.repository.Repository;/*** @since 1.2.0*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {/*** 指定不会自动配置的类*/@AliasFor(annotation = EnableAutoConfiguration.class)Class<?>[] exclude() default {};/*** 指定不会自动配置类类名*/@AliasFor(annotation = EnableAutoConfiguration.class)String[] excludeName() default {};/*** 扫描的包路径*/@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")String[] scanBasePackages() default {};@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")Class<?>[] scanBasePackageClasses() default {};@AliasFor(annotation = ComponentScan.class, attribute = "nameGenerator")Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;@AliasFor(annotation = Configuration.class)boolean proxyBeanMethods() default true;}
- 使用 @SpringbootApplication注解等价于 使用@SpringBootConfiguration ,@EnableAutoConfiguration和@ComponentScan三个注解;
- SpringBootConfiguration:标注类为配置类
- EnableAutoConfiguration:开启自动配置
- ComponentScan:组件扫描
- SpringBootApplication中的属性都是另外三个注解中属性别名;
- SpringBootApplicaion中只是把其他三个注解中常用的属性做了别名设置,但并不是全部,以ComponentScan为例
ComponentScan注解源代码如下所示:
package org.springframework.context.annotation;import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.core.annotation.AliasFor;
import org.springframework.core.type.filter.TypeFilter;/*** @since 3.1* @see Configuration*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan {/*** basePackages 别名*/@AliasFor("basePackages")String[] value() default {};/*** 基础包路径*/@AliasFor("value")String[] basePackages() default {};Class<?>[] basePackageClasses() default {};Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;/*** The {@link ScopeMetadataResolver} to be used for resolving the scope of detected components.*/Class<? extends ScopeMetadataResolver> scopeResolver() default AnnotationScopeMetadataResolver.class;ScopedProxyMode scopedProxy() default ScopedProxyMode.DEFAULT;String resourcePattern() default ClassPathScanningCandidateComponentProvider.DEFAULT_RESOURCE_PATTERN;boolean useDefaultFilters() default true;Filter[] includeFilters() default {};/*** Specifies which types are not eligible for component scanning.* @see #resourcePattern*/Filter[] excludeFilters() default {};/*** Specify whether scanned beans should be registered for lazy initialization.* <p>Default is {@code false}; switch this to {@code true} when desired.* @since 4.1*/boolean lazyInit() default false;/*** Declares the type filter to be used as an {@linkplain ComponentScan#includeFilters* include filter} or {@linkplain ComponentScan#excludeFilters exclude filter}.*/@Retention(RetentionPolicy.RUNTIME)@Target({})@interface Filter {FilterType type() default FilterType.ANNOTATION;@AliasFor("classes")Class<?>[] value() default {};@AliasFor("value")Class<?>[] classes() default {};String[] pattern() default {};}}
2.2 高度定制
如果想要定制springboot应用,直接 使用@SpringBootConfiguration ,@EnableAutoConfiguration和@ComponentScan三个注解代替@SpringBootApplication,根据需要设置相应的属性值。
这里只做简单的介绍,后续会深入分析springboot相关的底层原理。
3 springboot各种配置优先级顺序
- springboot提供的配置位置(方式)
在springboot官网文档Externalized Configuration(外部化配置)中有详细解析介绍各种配置。
这里我们主要看下常用的配置优先级,配置优先级顺序由低到高如下所示:
- 默认配置 (通过
SpringApplication.setDefaultProperties
设置). @PropertySource
注解,在@Configuration标记的类上使用.- 配置文件 (例如
application.properties或者applicaiton.yml
). random.*
设置属性.- 系统环境变量.
- Java系统属性 (
System.getProperties()
). - JNDI attributes from
java:comp/env
. ServletContext
init parameters.ServletConfig
init parameters.- SPRING_APPLICATION_JSON`内置json格式参数设置。
- 命令行参数.
properties
attribute on your tests. Available on@SpringBootTest
and the test annotations for testing a particular slice of your application.@TestPropertySource
annotations on your tests.- Devtools global settings properties in the
$HOME/.config/spring-boot
directory when devtools is active.
- 12,13,14和测试相关,7,8,9不常用
下面简单演示下其他配置方式,以配置启动端口为例
- 默认配置
简单起见,我们直接在启动类的main方法中演示,代码如下3-1所示:
public static void main(String[] args) {SpringApplication application = new SpringApplication(MyApplication.class);Map<String, Object> map = new HashMap<>();map.put("server.port", 8081);application.setDefaultProperties(map);application.run(args);
}
- @PropertySource,默认应用加载类路径下的applicaiton.properties或者application.yml配置文件,通过该注解修改加载指定的配置文件。
示例在类路径下创建gaogzhen.properties文件,内容:server.port=8082
,启动类添加如下注解:
@PropertySource("classpath:gaogzhen.properties")
- 配置数据,我们最常用的配置方式。
我们以application.yml文件为例,在类路径下创建application.yml文件,内容如下:
server:port: 8083
注:如果application.properties和application.yml同时配置,那么同名的key,application.properties中的配置值生效。
- random.*设置属性
可以在@Value,配置文件,System.getProperty(),命令行等位置配置,这里以.yml配置文件为例,如下所示:
my:secret: "${random.value}"number: "${random.int}"bignumber: "${random.long}"uuid: "${random.uuid}"number-less-than-ten: "${random.int(10)}"number-in-range: "${random.int[1024,65536]}"
- 系统环境变量
我们通过Idea临时设置下系统环境变量,做下演示,如下图所示:
- Java 系统属性(System.getProperties()),通过设置VM 参数的形式
示例如下图所示:
- SPRING_APPLICATION_JSON`内置json格式参数设置。
直接引用官网示例,
SPRING_APPLICATION_JSON='{"my":{"name":"test"}}' java -jar myapp.jar
java -Dspring.application.json='{"my":{"name":"test"}}' -jar myapp.jarjava -jar myapp.jar --spring.application.json='{"my":{"name":"test"}}'
- 命令行设置参数,前面需要固定符号–,如果不想要命令行参数添加到Enviroment中,通过执行
SpringApplication.setAddCommandLineProperties(false)
即可。
示例:
java -jar xxx.jar --server.port=8088
4 sprinboot配置文件解析顺序
这里没仔细研究,可以参考后面的视频或者文章不在详述。
结语
如果小伙伴什么问题或者指教,欢迎交流。
❓QQ:806797785
⭐️源代码仓库地址:https://gitee.com/gaogzhen/springboot-custom
参考:
[1]Springboot视频教程[CP/OL].P10,11,20,21.
[2]源码层面分析Springboot 配置文件加载顺序[CP/OL].