前言
Springboot是时下非常热门的java开发框架,它采用约定大于配置的开发理念,使我们几乎以零配置的方式快速构建一个java项目,非常优雅!
什么是Spring Boot?
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。简而言之,Spring Boot通过提供默认配置的方式整合了所有的框架,让我们可以更加简单、快速、方便地构建应用程序。
为什么要用Spring Boot?
Spring Boot包含以下几个特性:
默认提供了大部分框架的使用方式,方便进行快速集成
Spring Boot应用可以独立运行,符合微服务的开发理念
Spring Boot内置WEB容器,无需部署WAR包即可运行
提供了各种生产就绪型功能,如指标,健康检查和外部配置
Spring Boot通过网站提供了项目模板,方便项目的初始化
通过以上这些非常优秀的特性,Spring Boot可以帮助我们非常简单、快速的构建起我们的项目,并能够非常方便进行后续开发、测试和部署。
话不多说,学习一门新技术从“HelloWorld”开始是再合适不过的了!
一、开发第一个 Spring Boot 应用
下面会介绍maven和springboot脚手架2种方式开始我们的springboot之旅
环境准备
JDK 环境必须是 1.8 及以上
IDEA 2021.1.3
Maven 3.6.3
方式一:Maven工程
(1)创建maven项目
可以看见这是一个非常存粹的maven项目,和springboot没有任何关系!
(2)引入spring-boot-starter-parent依赖
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>maven-helloworld</artifactId>
<version>1.0-SNAPSHOT</version>
<!--springboot父依赖-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
</project>
spring-boot-starter-parent是springboot项目用于管理jar包版本的,也就是我们经常说的“版本仲裁”,记住它仅仅是管理版本的,并不会导入依赖,记住这点非常重要!我以前就搞混淆了,害我迷惑很长一段时间!!!
关于这一点我们可以用mvn dependency:tree查看项目依赖来验证,发现依赖为空!Good Gay!
[INFO] --- maven-dependency-plugin:3.1.2:tree (default-cli) @ maven-helloworld ---[INFO] org.example:maven-helloworld:jar:1.0-SNAPSHOT
从上面可以看到,我构建这个工程使用的是springboot 2.5.6版本,它集成的第三方依赖版本属性如下:
<properties>
<activemq.version>5.16.3</activemq.version>
<antlr2.version>2.7.7</antlr2.version>
<appengine-sdk.version>1.9.91</appengine-sdk.version>
<artemis.version>2.17.0</artemis.version>
<aspectj.version>1.9.7</aspectj.version>
<assertj.version>3.19.0</assertj.version>
<atomikos.version>4.0.6</atomikos.version>
<awaitility.version>4.0.3</awaitility.version>
<build-helper-maven-plugin.version>3.2.0</build-helper-maven-plugin.version>
<byte-buddy.version>1.10.22</byte-buddy.version>
<caffeine.version>2.9.2</caffeine.version>
<cassandra-driver.version>4.11.3</cassandra-driver.version>
<classmate.version>1.5.1</classmate.version>
<commons-codec.version>1.15</commons-codec.version>
<commons-dbcp2.version>2.8.0</commons-dbcp2.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
<commons-pool.version>1.6</commons-pool.version>
<commons-pool2.version>2.9.0</commons-pool2.version>
<couchbase-client.version>3.1.7</couchbase-client.version>
<db2-jdbc.version>11.5.6.0</db2-jdbc.version>
<dependency-management-plugin.version>1.0.11.RELEASE</dependency-management-plugin.version>
<derby.version>10.14.2.0</derby.version>
<dropwizard-metrics.version>4.1.26</dropwizard-metrics.version>
<ehcache.version>2.10.9.2</ehcache.version>
<ehcache3.version>3.9.7</ehcache3.version>
<elasticsearch.version>7.12.1</elasticsearch.version>
<embedded-mongo.version>3.0.0</embedded-mongo.version>
<flyway.version>7.7.3</flyway.version>
<freemarker.version>2.3.31</freemarker.version>
<git-commit-id-plugin.version>4.0.5</git-commit-id-plugin.version>
<glassfish-el.version>3.0.4</glassfish-el.version>
<glassfish-jaxb.version>2.3.5</glassfish-jaxb.version>
<groovy.version>3.0.9</groovy.version>
<gson.version>2.8.8</gson.version>
<h2.version>1.4.200</h2.version>
<hamcrest.version>2.2</hamcrest.version>
<hazelcast.version>4.1.5</hazelcast.version>
<hazelcast-hibernate5.version>2.2.1</hazelcast-hibernate5.version>
<hibernate.version>5.4.32.Final</hibernate.version>
<hibernate-validator.version>6.2.0.Final</hibernate-validator.version>
<hikaricp.version>4.0.3</hikaricp.version>
<hsqldb.version>2.5.2</hsqldb.version>
<htmlunit.version>2.49.1</htmlunit.version>
<httpasyncclient.version>4.1.4</httpasyncclient.version>
<httpclient.version>4.5.13</httpclient.version>
<httpclient5.version>5.0.4</httpclient5.version>
<httpcore.version>4.4.14</httpcore.version>
<httpcore5.version>5.1.2</httpcore5.version>
<infinispan.version>12.1.7.Final</infinispan.version>
<influxdb-java.version>2.21</influxdb-java.version>
<jackson-bom.version>2.12.5</jackson-bom.version>
<jakarta-activation.version>1.2.2</jakarta-activation.version>
<jakarta-annotation.version>1.3.5</jakarta-annotation.version>
<jakarta-jms.version>2.0.3</jakarta-jms.version>
<jakarta-json.version>1.1.6</jakarta-json.version>
<jakarta-json-bind.version>1.0.2</jakarta-json-bind.version>
<jakarta-mail.version>1.6.7</jakarta-mail.version>
<jakarta-management.version>1.1.4</jakarta-management.version>
<jakarta-persistence.version>2.2.3</jakarta-persistence.version>
<jakarta-servlet.version>4.0.4</jakarta-servlet.version>
<jakarta-servlet-jsp-jstl.version>1.2.7</jakarta-servlet-jsp-jstl.version>
<jakarta-transaction.version>1.3.3</jakarta-transaction.version>
<jakarta-validation.version>2.0.2</jakarta-validation.version>
<jakarta-websocket.version>1.1.2</jakarta-websocket.version>
<jakarta-ws-rs.version>2.1.6</jakarta-ws-rs.version>
<jakarta-xml-bind.version>2.3.3</jakarta-xml-bind.version>
<jakarta-xml-soap.version>1.4.2</jakarta-xml-soap.version>
<jakarta-xml-ws.version>2.3.3</jakarta-xml-ws.version>
<janino.version>3.1.6</janino.version>
<javax-activation.version>1.2.0</javax-activation.version>
<javax-annotation.version>1.3.2</javax-annotation.version>
<javax-cache.version>1.1.1</javax-cache.version>
<javax-jaxb.version>2.3.1</javax-jaxb.version>
<javax-jaxws.version>2.3.1</javax-jaxws.version>
<javax-jms.version>2.0.1</javax-jms.version>
<javax-json.version>1.1.4</javax-json.version>
<javax-jsonb.version>1.0</javax-jsonb.version>
<javax-mail.version>1.6.2</javax-mail.version>
<javax-money.version>1.1</javax-money.version>
<javax-persistence.version>2.2</javax-persistence.version>
<javax-transaction.version>1.3</javax-transaction.version>
<javax-validation.version>2.0.1.Final</javax-validation.version>
<javax-websocket.version>1.1</javax-websocket.version>
<jaxen.version>1.2.0</jaxen.version>
<jaybird.version>4.0.4.java8</jaybird.version>
<jboss-logging.version>3.4.2.Final</jboss-logging.version>
<jboss-transaction-spi.version>7.6.1.Final</jboss-transaction-spi.version>
<jdom2.version>2.0.6</jdom2.version>
<jedis.version>3.6.3</jedis.version>
<jersey.version>2.33</jersey.version>
<jetty-el.version>9.0.52</jetty-el.version>
<jetty-jsp.version>2.2.0.v201112011158</jetty-jsp.version>
<jetty-reactive-httpclient.version>1.1.10</jetty-reactive-httpclient.version>
<jetty.version>9.4.44.v20210927</jetty.version>
<jmustache.version>1.15</jmustache.version>
<johnzon.version>1.2.14</johnzon.version>
<jolokia.version>1.6.2</jolokia.version>
<jooq.version>3.14.15</jooq.version>
<json-path.version>2.5.0</json-path.version>
<json-smart.version>2.4.7</json-smart.version>
<jsonassert.version>1.5.0</jsonassert.version>
<jstl.version>1.2</jstl.version>
<jtds.version>1.3.1</jtds.version>
<junit.version>4.13.2</junit.version>
<junit-jupiter.version>5.7.2</junit-jupiter.version>
<kafka.version>2.7.1</kafka.version>
<kotlin.version>1.5.31</kotlin.version>
<kotlin-coroutines.version>1.5.2</kotlin-coroutines.version>
<lettuce.version>6.1.5.RELEASE</lettuce.version>
<liquibase.version>4.3.5</liquibase.version>
<log4j2.version>2.14.1</log4j2.version>
<logback.version>1.2.6</logback.version>
<lombok.version>1.18.22</lombok.version>
<mariadb.version>2.7.4</mariadb.version>
<maven-antrun-plugin.version>1.8</maven-antrun-plugin.version>
<maven-assembly-plugin.version>3.3.0</maven-assembly-plugin.version>
<maven-clean-plugin.version>3.1.0</maven-clean-plugin.version>
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
<maven-dependency-plugin.version>3.1.2</maven-dependency-plugin.version>
<maven-deploy-plugin.version>2.8.2</maven-deploy-plugin.version>
<maven-enforcer-plugin.version>3.0.0</maven-enforcer-plugin.version>
<maven-failsafe-plugin.version>2.22.2</maven-failsafe-plugin.version>
<maven-help-plugin.version>3.2.0</maven-help-plugin.version>
<maven-install-plugin.version>2.5.2</maven-install-plugin.version>
<maven-invoker-plugin.version>3.2.2</maven-invoker-plugin.version>
<maven-jar-plugin.version>3.2.0</maven-jar-plugin.version>
<maven-javadoc-plugin.version>3.2.0</maven-javadoc-plugin.version>
<maven-resources-plugin.version>3.2.0</maven-resources-plugin.version>
<maven-shade-plugin.version>3.2.4</maven-shade-plugin.version>
<maven-source-plugin.version>3.2.1</maven-source-plugin.version>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
<maven-war-plugin.version>3.3.2</maven-war-plugin.version>
<micrometer.version>1.7.5</micrometer.version>
<mimepull.version>1.9.15</mimepull.version>
<mockito.version>3.9.0</mockito.version>
<mongodb.version>4.2.3</mongodb.version>
<mssql-jdbc.version>9.2.1.jre8</mssql-jdbc.version>
<mysql.version>8.0.27</mysql.version>
<nekohtml.version>1.9.22</nekohtml.version>
<neo4j-java-driver.version>4.2.7</neo4j-java-driver.version>
<netty.version>4.1.69.Final</netty.version>
<netty-tcnative.version>2.0.44.Final</netty-tcnative.version>
<oauth2-oidc-sdk.version>9.9.1</oauth2-oidc-sdk.version>
<nimbus-jose-jwt.version>9.10.1</nimbus-jose-jwt.version>
<ojdbc.version>19.3.0.0</ojdbc.version>
<okhttp3.version>3.14.9</okhttp3.version>
<oracle-database.version>21.1.0.0</oracle-database.version>
<pooled-jms.version>1.2.2</pooled-jms.version>
<postgresql.version>42.2.24</postgresql.version>
<prometheus-pushgateway.version>0.10.0</prometheus-pushgateway.version>
<quartz.version>2.3.2</quartz.version>
<querydsl.version>4.4.0</querydsl.version>
<r2dbc-bom.version>Arabba-SR11</r2dbc-bom.version>
<rabbit-amqp-client.version>5.12.0</rabbit-amqp-client.version>
<reactive-streams.version>1.0.3</reactive-streams.version>
<reactor-bom.version>2020.0.12</reactor-bom.version>
<rest-assured.version>4.3.3</rest-assured.version>
<rsocket.version>1.1.1</rsocket.version>
<rxjava.version>1.3.8</rxjava.version>
<rxjava-adapter.version>1.2.1</rxjava-adapter.version>
<rxjava2.version>2.2.21</rxjava2.version>
<saaj-impl.version>1.5.3</saaj-impl.version>
<selenium.version>3.141.59</selenium.version>
<selenium-htmlunit.version>2.49.1</selenium-htmlunit.version>
<sendgrid.version>4.7.6</sendgrid.version>
<servlet-api.version>4.0.1</servlet-api.version>
<slf4j.version>1.7.32</slf4j.version>
<snakeyaml.version>1.28</snakeyaml.version>
<solr.version>8.8.2</solr.version>
<spring-amqp.version>2.3.11</spring-amqp.version>
<spring-batch.version>4.3.3</spring-batch.version>
<spring-data-bom.version>2021.0.6</spring-data-bom.version>
<spring-framework.version>5.3.12</spring-framework.version>
<spring-hateoas.version>1.3.5</spring-hateoas.version>
<spring-integration.version>5.5.5</spring-integration.version>
<spring-kafka.version>2.7.8</spring-kafka.version>
<spring-ldap.version>2.3.4.RELEASE</spring-ldap.version>
<spring-restdocs.version>2.0.5.RELEASE</spring-restdocs.version>
<spring-retry.version>1.3.1</spring-retry.version>
<spring-security.version>5.5.3</spring-security.version>
<spring-session-bom.version>2021.0.3</spring-session-bom.version>
<spring-ws.version>3.1.1</spring-ws.version>
<sqlite-jdbc.version>3.34.0</sqlite-jdbc.version>
<sun-mail.version>1.6.7</sun-mail.version>
<thymeleaf.version>3.0.12.RELEASE</thymeleaf.version>
<thymeleaf-extras-data-attribute.version>2.0.1</thymeleaf-extras-data-attribute.version>
<thymeleaf-extras-java8time.version>3.0.4.RELEASE</thymeleaf-extras-java8time.version>
<thymeleaf-extras-springsecurity.version>3.0.4.RELEASE</thymeleaf-extras-springsecurity.version>
<thymeleaf-layout-dialect.version>2.5.3</thymeleaf-layout-dialect.version>
<tomcat.version>9.0.54</tomcat.version>
<unboundid-ldapsdk.version>4.0.14</unboundid-ldapsdk.version>
<undertow.version>2.2.12.Final</undertow.version>
<versions-maven-plugin.version>2.8.1</versions-maven-plugin.version>
<webjars-hal-browser.version>3325375</webjars-hal-browser.version>
<webjars-locator-core.version>0.46</webjars-locator-core.version>
<wsdl4j.version>1.6.3</wsdl4j.version>
<xml-maven-plugin.version>1.0.2</xml-maven-plugin.version>
<xmlunit2.version>2.8.3</xmlunit2.version>
</properties>
(3)引入spring-boot-starter-web启动器
接下来,我们把项目改造成一个web工程!
以前我们创建web工程,需要引入很多依赖,有了springboot后我们只需要引入spring-boot-starter-web启动器
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>maven-helloworld</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!--引入web启动器-->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
引入web的starter依赖后,刷新一下maven,再次用mvn dependency:tree 查看依赖树:
[INFO] org.example:maven-helloworld:jar:1.0-SNAPSHOT
[INFO] \- org.springframework.boot:spring-boot-starter-web:jar:2.5.6:compile
[INFO] +- org.springframework.boot:spring-boot-starter:jar:2.5.6:compile
[INFO] | +- org.springframework.boot:spring-boot:jar:2.5.6:compile
[INFO] | +- org.springframework.boot:spring-boot-autoconfigure:jar:2.5.6:compile
[INFO] | +- org.springframework.boot:spring-boot-starter-logging:jar:2.5.6:compile
[INFO] | | +- ch.qos.logback:logback-classic:jar:1.2.6:compile
[INFO] | | | +- ch.qos.logback:logback-core:jar:1.2.6:compile
[INFO] | | | \- org.slf4j:slf4j-api:jar:1.7.32:compile
[INFO] | | +- org.apache.logging.log4j:log4j-to-slf4j:jar:2.14.1:compile
[INFO] | | | \- org.apache.logging.log4j:log4j-api:jar:2.14.1:compile
[INFO] | | \- org.slf4j:jul-to-slf4j:jar:1.7.32:compile
[INFO] | +- jakarta.annotation:jakarta.annotation-api:jar:1.3.5:compile
[INFO] | +- org.springframework:spring-core:jar:5.3.12:compile
[INFO] | | \- org.springframework:spring-jcl:jar:5.3.12:compile
[INFO] | \- org.yaml:snakeyaml:jar:1.28:compile
[INFO] +- org.springframework.boot:spring-boot-starter-json:jar:2.5.6:compile
[INFO] | +- com.fasterxml.jackson.core:jackson-databind:jar:2.12.5:compile
[INFO] | | +- com.fasterxml.jackson.core:jackson-annotations:jar:2.12.5:compile
[INFO] | | \- com.fasterxml.jackson.core:jackson-core:jar:2.12.5:compile
[INFO] | +- com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.12.5:compile
[INFO] | +- com.fasterxml.jackson.datatype:jackson-datatype-jsr310:jar:2.12.5:compile
[INFO] | \- com.fasterxml.jackson.module:jackson-module-parameter-names:jar:2.12.5:compile
[INFO] +- org.springframework.boot:spring-boot-starter-tomcat:jar:2.5.6:compile
[INFO] | +- org.apache.tomcat.embed:tomcat-embed-core:jar:9.0.54:compile
[INFO] | +- org.apache.tomcat.embed:tomcat-embed-el:jar:9.0.54:compile
[INFO] | \- org.apache.tomcat.embed:tomcat-embed-websocket:jar:9.0.54:compile
[INFO] +- org.springframework:spring-web:jar:5.3.12:compile
[INFO] | \- org.springframework:spring-beans:jar:5.3.12:compile
[INFO] \- org.springframework:spring-webmvc:jar:5.3.12:compile
[INFO] +- org.springframework:spring-aop:jar:5.3.12:compile
[INFO] +- org.springframework:spring-context:jar:5.3.12:compile
[INFO] \- org.springframework:spring-expression:jar:5.3.12:compile
好家伙,仅仅是引入了一个web的starter,springboot就会默认为我们下载web工程所有依赖的jar,这正是springboot简化开发的第一步,所有开发场景都给你集成一个starter!
(4)新建启动类
package com.huiwei.hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@EnableAutoConfiguration
@ComponentScan
//@SpringBootApplication //可以代替上面2个注解
public class HelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldApplication.class,args);
}
}
注意:@SpringBootApplication注解包含了@EnableAutoConfiguration、@ComponentScan、@SpringBootConfiguration这3个注解,所以可以用这一个注解代替3个注解
(5)创建HelloController来进行测试
package com.huiwei.hello.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("hello")
public String hello(){
return "Hello,Spring!";
}
}
(6)启动项目,访问测试:http://localhost:8080/hello
(7)创建可执行 jar
要创建可执行 jar,我们需要将 spring-boot-maven-plugin 添加到 pom.xml 文件中。在 dependencies 下方插入以下配置:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
引入依赖后,刷新maven,双击idea右侧的package,进行打包
生成maven-helloworld-1.0-SNAPSHOT.jar
在命令行执行java -jar maven-helloworld-1.0-SNAPSHOT.jar,这样就以jar包的方式启动了一个springboot工程
方式二:使用springboot脚手架创建项目
(1)选择左边的Spring Initializr
(2)选择web的依赖,点击完成创建springboot脚手架
当我们经过以上2步创建一个springboot工程后,创建好的项目结构如下:
我们可以看见这种方式已经默认帮我们创建了项目的启动类
package com.example.springboothello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootHelloApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootHelloApplication.class, args);
}
}
此外还在resources资源目录下创建了
static文件夹:用于存放静态资源文件
templates文件夹:用于存放模板文件
application.properties:用于修改项目的一些默认配置
我们打开pom文件如下:
<?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>2.5.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>springboot-hello</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-hello</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<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>
</plugins>
</build>
</project>
好家伙,已经为我们默认引入了parent依赖、web依赖以及一个test的依赖,还有项目进行打包的依赖,不用我们手动引入了,我们想要什么功能只需要在创建项目时勾选相应的模块即可!
(3)创建HelloController用于测试
package com.example.springboothello.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("hello")
public String hello(){
return "Hello,springboot-hello!";
}
}
(4)启动访问:http://localhost:8080/hello
二、SpringbootApplication启动类详解
Spring Boot 项目通常有一个名为 XXXApplication 的入口类,入口类里有一个 main 方法, 这个 main 方法其实就是一个标准的 Java应用的入口方法。
@SpringBootApplication
public class SpringbootHelloApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootHelloApplication.class, args);
}
}
当我们启动这个类时,会运行SpringApplication的run方法,run方法传入了启动类SpringbootHelloApplication 的class对象,然后对启动类的注解@SpringBootApplication进行解析,我们来看看@SpringBootApplication的内部
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
可以看到,它由@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan三个注解组成
@SpringBootConfiguration是spring原生注解Configuration的springboot版本
@EnableAutoConfiguration让 Spring Boot 根据类路径中的 jar 包依赖为当前项目进行自动配置,例如,添加了 spring-boot-starter-web 依赖,会自动添加Tomcat 和 Spring MVC 的依赖,那么 Spring Boot 会对 Tomcat 和 Spring MVC 进行自动配置。
Spring Boot 还会自动扫描 @SpringBootApplication 所在类的同级包以及下级包里的 Bean ,所以入口类建议就配置在 grounpID + arctifactID 组合的包名下
三、springboot配置文件
Spring Boot 使用一个全局的配置文件 application.properties 或 application.yml,放置在【src/main/resources】目录或者类路径的 /config 下。
Spring Boot 不仅支持常规的 properties 配置文件,还支持 yaml 语言的配置文件。yaml 是以数据为中心的语言,在配置数据的时候具有面向对象的特征。
Spring Boot 的全局配置文件的作用是对一些默认配置的配置值进行修改。
修改 properties 配置文件实例:
(1)打开 resources 下的 application.properties
(2)在这里我们可以设置访问的端口,将 Tomcat 默认端口设置为 8082 ,并将默认的访问路径从 “/” 修改为 “/springboot” 时,再访问 http://localhost:8080/hello是什么都没有的
此时要访问 hello 是要使用 http://localhost:8082/springboot/hello
(3)使用 yml 文件作为配置文件
重启项目进行访问:
(4)yml语法
基本语法
k:(空格)v:表示一对键值对(空格必须有);
以空格的缩进来控制层级关系;只要是左对齐的一列数据,都是同一个层级的
此外,属性和值也是大小写敏感;
值的写法
字面量:普通的值(数字,字符串,布尔)
k: v:字面直接来写;
name: 小明
age: 18
字符串默认不用加上单引号或者双引号;
"":双引号;不会转义字符串里面的特殊字符;特殊字符会作为本身想表示的意思
name: "zhangsan \n lisi":输出;zhangsan 换行 lisi
'':单引号;会转义特殊字符,特殊字符最终只是一个普通的字符串数据
name: ‘zhangsan \n lisi’:输出;zhangsan \n lisi
对象、Map(属性和值)(键值对)
k: v:在下一行来写对象的属性和值的关系;注意缩进
friends:
lastName: zhangsan
age: 20
行内写法:
friends: {lastName: zhangsan,age: 18}
数组(List、Set)
用- 值表示数组中的一个元素
pets:
- cat
- dog
- pig
行内写法
pets: [cat,dog,pig]
(5)@value获取配置文件属性
在application.yml中配置person,name为小明,年龄为18
server:
port: 8085
person:
name: 小明
age: 18
在我们的HelloController中用@value来获取配置属性,
@RestController
public class HelloController {
@Value("${person.name}")
String name;
@Value("${person.age}")
Integer age;
@RequestMapping("hello")
public String hello(){
return "Hello,"+name+",今年"+age+"岁";
}
}
重启项目,访问 http://localhost:8085/hello,结果如下:
(6)封装配置信息使用方法
@value尽管可以封装配置信息,但当相关连的配置信息太多时,我们可以对信息进行封装
我们构建一个Person对象,里面包含了字符串、数字、布尔、日期、map、数组、对象等各种类型的属性,正好可以对上面的yml语法进行验证
String lastName
Integer age
Boolean boss
Date birth
Map<String,Object> maps
List<Object> lists
Dog dog
1)application.yml 文件内容如下:
person:
lastName: 小明
age: 18
boss: false
birth: 2017/12/12
maps: {k1: v1,k2: 12}
lists:
- lisi
- zhaoliu
dog:
name: 小狗
age: 12
2)新建 Person.java 和 HelloController.java ,内容如下:
Person.java:
package com.example.springboothello.bean;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component
@Data
@ConfigurationProperties(prefix = "person")
public class Person {
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
}
HelloController.java:
package com.example.springboothello.controller;
import com.example.springboothello.bean.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Autowired
Person person;
@RequestMapping("hello")
public String hello(){
return person.toString();
}
}
3)访问 http://localhost:8080/hello 结果如下:
解释:我们可以把配置信息封装成一个类,首先在我们的属性前加一个 person前缀,然后新建一个 Person类用来封装这些信息,并用上两个注解:
@Component:表明当前类是一个 Java Bean
@ConfigurationProperties(prefix = “person”):表示获取前缀为person的配置信息
喜欢的朋友记得点赞、收藏、关注哦!!!