Spring Boot简介

Spring Boot是由Pivotal团队开发的Spring框架,采用了生产就绪的观点,旨在简化配置,致力于快速开发。Spring Boot 框架提供了自动装配和起步依赖,使开发人员不需要配置各种xml文件。通过这种方式,极大地提高了程序的开发速度。因此,Spring Boot被认为是新一代的Web开发框架。

 

在过去的Spring开发中,需要引入大量的xml文件。Spring2.5 引入了包扫描,消除了显式的配置Bean。Spring 3.0又引入了基于JavaBean的配置,这种方式可以取代xml文件。尽管如此,在实际的开发中还是需要配置xml文件,例如配置SpringMVC、事务管理器、过滤器、切面等。

在项目的开发过程中,会引入大量的第三方依赖,选择依赖是一件不容易的事,解决依赖与依赖之间的冲突也很耗费精力。所以,在以前的Spring开发中,依赖管理也是一-件棘手的事情。

Pivotal 团队提供的Spring Boot框架,解决了以前Spring应用程序开发的痛点。

Spring Boot的特点

对比之前的Spring, Spring Boot有三大特点:自动配置、 起步依赖和Actuator对运行状态的监控。

自动配置就是程序需要什么,Spring Boot就会装配什么。例如,当程序的pom文件引入了Feign的起步依赖,Spring Boot就会在程序中自动引入默认的Feign 的配置Bean.再例如配置Feign的Decoder时,如果开发人员配置了Decoder Bean, Spring Boot就不会引入默认的Decoder Bean。自动装配使得程序开发变得非常便捷、智能化。

在以前开发过程中,向项目添加依赖是-一件非常有挑战的事情。选择版本,解决版本冲突,十分耗费精力。例如,程序需要Spring MVC的功能,那么需要引入spring .core、spring-web和spring-webmve 等依赖,但是如果程序使用Spring Boot 的起步依赖,只需要加入spring boot-starter-wveb的依赖,它会自动引入Spring MVC功能的相关依赖。

SpringBoot能够提供自动装配和起步依赖,解决了以前重量级的xml配置和依赖管理的各种问题。一切都显得那么敏捷、智能,但是却带来了一系列的其他问题:开发者该怎么知道应用程序中注入了哪些Bean?应用程序的运行状态是怎么样的?为了解决这些问题,SpringBoot提供了Actuator 组件,并提供了对程序的运行状态的监控功能。

Spring Boot的优点

Spring Boot不仅提供了自动装配、起步依赖,还自带了不少非功能性的特性,例如安全、度量、健康检查、内嵌Servlet容器和外置配置。开发人员可以更加敏捷快速地开发Spring程序,专注于应用程序本身的业务开发,而不是在Spring的配置上花费大量的精力。

另外,Actuator提供了运行时的SpringBoot程序中的监控端点,让开发人员和运维人员实时了解程序的运行状况。

 

用IDEA构建Spring Boot工程

打开"IDEA"-“new Projct"→“Spring Iitializr”"→填写“group"和“artifact"→勾选“web"(开启web功能)→单击“下一步”。IDEA 会自动下载Spring Boot工程的模板。

项目 结构

创建完工程后,工程的目录结构如下:

src
-main
-Java
- package
-SpringbootApplication
- resouces
- statics
- templates
- -application . yml
-test
- ***

各目录含义如下。

  • pom文件为依赖管理文件。

  • resouces

  • 为资源文件夹。98

  • statics为静态资源。

  • templates为模板资源。

  • application.yml为配置文件。

  • SpringbootApplication为程序的启动类。

在Spring Boot工程中构建Web

打开用IDEA创建的项目,其依赖管理文件pom.xml 有spring-boot-starter-web 和spring-boot- starter-test的起步依赖。其中,spring-boo-tarter-web 为Web功能的起步依赖,它会自动导入与Web相关的依赖。spring-boot-starter-test 为Spring Boot测试功能的起步依赖,它会导入与Spring Boot测试相关的依赖。代码如下:

<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 >

在工程的代码包的主目录下有一个
SpringbootFirstApplication的类,该类是程序的启动类,代码如下:

@SpringBootApplication
public class SpringbootFirs tApplication {
public static void main(String[] args) {
SpringApplication. run (SpringbootFirstApplication.class, args) ;
}}

其中,@ SpringBootApplication注解包含了@SpringBootConfiguration、@EnableAuto-Configuration和@ComponentScan,开启了包扫描、配置和自动配置的功能。

这是一个完整的、具有Web功能的工程,为了演示Web效果,建一个Web层的Controller,代码如下:

@RestController
public class HelloController {
@RequestMapping (" /hello")
public String index() {
return "Greetings from Spring Boot!";
}
}

其中,@RestController 注解表明这个类是一一个RestController。@RestController 是Spring 4.0版本的一个注解,它的功能相当于@Controller注解和@ResponseBody注解之和。

@RequestMapping注解是配置请求地址的Url映射的。

启动SpringbotFirstApplication的main方法,Spring Boot程序启动。在控制台会打印启动的日志,程序的默认端口为8080。

打开浏览器,在浏览器上输入“htp://ocahost:8080/hello”"浏览器会显示“Greetings fromSpring Boot!'

你会不会觉得Spring Boot的确很神奇? Spring Boot的神奇之处在于,在程序中没有做web.xml的配置,也没有做SpringMVC的配置,甚至都不用部署在Tomcat上,就可以构建一一个具备Web功能的工程。其实,Spring Boot自动为你做了这些配置,并且它默认内嵌了Tomcat容器。

Spring Boot的测试

Spring Boot开启测试也非常简单,只需要加@RunWith(SpringRunner.class)和@ SpringBootTest注解,在@SpringBootTest注解加上Web测试环境的端口为随机端口的配置。TestRestTemplate类为RestTemplate测试类,RestTemplate 用于远程调用Http API接口。测试代码如下:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnv ronment
= SpringBootTest.WebEnvironment . RANDOM_PORT)
public class HelloControllerIT {
@LocalServerPort
pr vate
int port ;
private URL base;
@Au tow red
pr vate
TestRestTemplate template ;
@Before
public roid
setup () throws Exception {
this . base = new URL (” http : //localhost :” + port + ” / hello” ) ,
}
@Test
public roid
getHello() throws Except on
{
ResponseEntity<String> response= template . getForEntity(base toString() ,
Sti::ing . class);
assertThat(respo se get Body() , equal To (” Greetings from Spring Boot ! ” )) ;
}
}

启动测试类的getHello( )方法,通过控制台可以发现Spring Boot 程序会先启动,然后运行测试代码,最后测试通过。

Spring Boot配置文件详解

Spring Boot 采用了构建生产就绪Spring应用程序的观点,旨在让程序快速启动和运行。

在一-般情况下,不需要做太多的配置就能够让SpringBoot程序正常运行。在--些特殊的情况下,我们需要修改一些配置,或者需要有自己的配置。

自定义属性

在用IDEA创建一一个 Spring Boot工程时,系统默认会在src/main/java/resources 目录下创建一个配置文件application.properties.它也支持yml格式的文件,下面以yml格式的文件为例来讲解如何自定义属性。

在工程的配置文件application.yml自定义- -组属性,如下:

my:
name: forezp
age: 12

如果要读取配置文件application.yml的属性值,只需在变量上加@Value("$ {属性名}")注

解,就可以将配置文件application.yml 的一个属性值赋给-一个变量。新建一 -个Controller, 其

代码清单如下:

@RestController
public class MiyaController {
@Value ("$ {my. name}")
private String name;
@Value ("$ {my.age}")
private int age;
@RequestMapping(value = " /miya")
public String miya() {
return name+":"+age;}
}

启动工程SpringBoot,打开浏览器访问“htp:p/ocahost:8080/omia",浏览器显示如下:

forezp:12

这说明配置文件application.yml的属性my.name和my.age已经成功读入应用程序中。

将配置 文件的属性赋给实体类

当有很多配置属性时,如果逐个地读取属性会非常麻烦。通常的做***把这些属性名作为变量名来创建一- 个JavaBean的变量,并将属性值赋给JavaBean变量的值。

在配置文件application.yml中添加如下属性:

my:
name: forezp
age: 12
number :
${ random. int}
uuid : $ {random. uuid}
max: ${random.int(10) }
value: $ {random. value}
greeting: hi,i'm $ {my. name }

其中,配置文件中用到了${random},它可以用来生成各种不同类型的随机值。random.int随机生成一一个int 类型的值,random.uuid 随机生成-一个uuid, random.value 随机生成- -个值,random.int(10)随机生成一个小于10的整数。

怎么将这些属性赋给-一个 JavaBean呢?创建-一个JavaBean,其代码清单如下:

@ConfigurationProperties (prefix = "my")
@Component
public class ConfigBean {
private String name;
private int age;
private int number ; !
private String uuid;
private int max;
private String value;
private String greeting;
//省略了getter setter....
)

在上面的代码中,在ConfigBean类上加一-个注解@ConfigurationProperties,表明该类为配置属性类,并加上配置的prefix, 例如本案例的“my"。另外需要在ConfigBean类上加@Component注解,SpringBoot在启动时通过包扫描将该类作为-一个Bean注入IoC容器中。

创建一个Controller,读取ConfigBean类的属性。在Controller类上,加

@
EnableConfigurationProperties注解,并指明ConfigBean 类,其代码清单如下:

@RestController
@EnableConf igurationProperties ({ConfigBean.class})
public class LucyController {
@Autowi red
ConfigBean configBean;
@RequestMapping(value = "/1ucy")
public String miya() {
return conf igBean. getGreeting () +"-"+conf igBean. getName ()+"-"+
configBean. getUuid()+ "-"+configBean.getMax() ;
}

启动工程,在浏览器上访问"“ttp://localhost:8080/lucy", 浏览器会显示从配置文件读取的属性。

自 定义配置文件

.上面介绍了如何把配置属性写到application.yml配置文件中,并把配置属性读取到-个配置类中。有时属性太多,把所有的配置属性都写到application.yml配置文件中不太合适,这时需要自定义配置文件。例如在src/main/resources目录下自定义一个test.properties配置文件,

其配置信息如下:

com. forezp . name=forezp
com. forezp.age=12

如何将这个配置文件test.properties的属性和属性值赋给- 个JavaBean呢?需要在类名上

加@Configuration、@PropertySource 和@ConfigurationProperties这3个注解。需要注意的是,若Spring Boot版本为1.4或1.4之前,则需要在@PropertySource注解上加location,并指明该配置文件的路径。本案例采用的Spring Boot版本为1.5,代码如下:

@Configuration
@Propertysource (value = "classpath: test .properties")
@ConfigurationProperties (prefix = "com. forezp")
public class User {
private String name;
private int age;
/..省略getter、setter
}

写一个LueyController的类,在类的上方加上@RestController 注解,开启RestControllerde的功能;加上@
EnableConfigurationProperties注解,并指明需要引用的JavaBean 的类,开启引用配置属性的功能,其代码清单如下:

@RestController
@EnableConfigurationProperties ({ConfigBean.class,User.class})
public class LucyController {
@Autowi red
ConfigBean configBean;
@RequestMapping(value = "/lucy")
public String miya() {
return configBean. getGreeting () +configBean. getName ()+
configBean. getUuid()+ configBean. getMax() ;
@Autowi red
User user;
@RequestMapping(value = "/user")
public String user() {
return user .getName()+": "+user .getAge() ;
}

启动工程,在浏览器上访问“htp://l/calhost:8080/user?”。浏览器会显示“forezp: 12 ”,这说明自定义配置文件的属性被读取到了JavaBean中。

多 个环境的配置文件

在实际的开发过程中,可能有多个不同环境的配置文件,例如:开发环境、测试环境、生产环境等。Spring Boot支持程序启动时在配置文件applicaition.yml 中指定环境的配置文件,配置文件的格式为application- {profile}.properties,其中{profile}对应环境标识,例如:

  • application-test.properties 测 试环境;

  • application-dev.properties 开发环境;

  • application-prod.properties-生产环境。

如何指定这个环境配置文件呢?只需要在application.yml中加上spring.profiles.active的配置,该配置指定采用哪一个profiles。例如使用
application-dev.properties,则配置代码如下:

spring:
profiles:
active: dev

其中,application-dev.yml 的配置文件中指定程序的启动端口,配置代码如下:

server:
port: 8082

启动工程,查看控制台打印的日志,程序的启动端口为8082,而不是默认的8080,这说明配置文件生效了。

另外,我们也可以通过java -jar这种方式启动程序,并指定程序的配置文件,启动命令如下:

$ java - jar spr ingbootdemo.jar -- spring .profiles .active=dev

 

运行状态监控Actuator

Spring Boot的Actuator提供了运行状态监控的功能,Actuator 的监控数据可以通过REST、远程shell和JMX方式获得。我们首先来介绍通过REST方式查看Actuator的节点的方法,这种是最常见且简单的方法。

在工程的pom文件中引入Actuator的起步依赖
spring-boot-starter-actuator,代码清单如下:

<dependency>
<groupId>org . spr ingf ramework. boot</groupId>
<arti factId>spring-boot-starter- actuator</artifactId>
</dependency>

在配置文件application.yml中配置management.port和
management.security.enabled, 这两个配置分别配置了Actuator 对外暴露REST API接口的端口号和Actuator采取非安全验证方式,其代码清单如下:

management:
port: 9001
security:
enabled:
false

在上述的配置代码中指定了Actuator 对外暴露REST API接口的端口为9001,如果不指定,端口为应用程序的启动端口,这样做的目的是将程序端口和程序的监控端口分开。SpringBoot 1.5x 版本默认开启了Actuator的安全验证,为了能够在浏览器上展示效果,不做安全验证,将management.security. enables-false。启动工程,在控制台可以看到如下信息:

Mapped" {[/autoconfigll/autoconfig.json] , me thods= [GET] ,produces= [application/vnd. sprin
gboot .actuator.v1+jsonII application/json] }"
Mapped"{ [/beansII/beans . json] ,methods= [GET], produces= [application/vnd. spring-boot. act
uator .vl+jsonllapplication/json]}"
Mapped"{[/tracell /trace.json] , methods= [GET] , produces= [application/vnd. spring-boot. act
uator.v1+json I I application/json]}"

Spring Boot Actuator 的关键特性是在应用程序里提供众多的Web节点,通过这些节点可以实时地了解应用程序的运行状况。有了Actuator, 你可以知道Bean在Spring应用程序上下文里是如何组装在-起的,并且可以获取环境属性的信息和运行时度量信息等。

Actuator提供了13个API接口,用于监控运行状态的Spring Boot 的状况,具体如表4-1所示。

 

 

查看 运行程序的健康状态

打开浏览器访问“
http://localhost:9091/heath", 可以查看应用程序的运行状态和磁盘状态等信息。浏览器显示的信息如下:

"status": "UP",
"diskSpace": {
"status": "UP",
"total": 392461021184,
"free": 381625602048,
"threshold": 10485760

“health"API接口提供的信息是由一一个或多个健康指示器提供的健康信息的组合结果。

如表4-2所示,列出了SpringBoot自带的健康指示器。

 

查看运行程序的 Bean

如果南耍了解. Spring Boot 文注入了哪 Bean ,这 Bean 类型、状 生命周期等信息 时, 只需要发起 GET 类型 求, API 为“ /beans ”, 览器上访问http:// locahost:9091 /beans 飞浏览器会显示如下的信息:

"context":” application : dev : 8082",
"parent": null,
"beans":I
"bean": "spr ingbootFirstApplication",
"aliases": [
],
"scope": "singleton",
"type": "com. forezp。Spr ingbootFirstApplicat ionSEnhance rBySpr ingCGLIB$$
3efbe85a",
"resource": "null",
"dependencies": [
"bean": "org . springframework . boot .autoconfigure . internalCachingMetadata
ReaderFactory",
"aliases": [
"scope": "singleton",
"type": "org . springframework . core . type . classreading。CachingMe tadataRead
erFactory",
"resource": "nul1",
"dependencies": [
"bean": "configBean" ,
"aliases": [
,
"scope": "singleton",
"type": "com. forezp . bean . ConfigBean",
  "resource": "file [F:/book/springboot-first-applicat ion/target/classes/
com/ forezp/bean/ConfigBean.class]",
"dependencies": [
"bean": "user",
"allases":I
),
"scope": "singleton",
"type": "com. forezp。bean. UserssEnhancerBySpr ingCGLIBseb8cd986",
"resource"; "file ,[F:/book/springboot-first-application/target/clases/
com/ forezp/bean/User。class]",
"dependencies": [
"bean": "helloController",
"aliases": l
],
"scope": "singleton",
"type": "com. forezp . web. Hel loController",
"resource": "file [F:/book/spr ingboot- first-application/target/classes/
com/ forezp/web/He11oController.c18s]".
"dependencies"; [
"bean": "lucyController" 。
"aliasea": [
],
"scope": "singleton",
"type": "com. forezp . web . LucyController,
"resource": "file [E:/book/springboot-first-appl ication/target/classes/
com/ forezp/web/LueyContro11er.c185s1".
"dependencies": [
"configBean",
"user"
...
  }

在返回的信息中包含了Bean的以下4类信息。

  • bean: Spring应用程序 上下文中的 Bean名称或Id.

  • resource: class 文件的物理位置,通常是一个Url,指向构建出的Jar文件的路径。

  • scope: Bean的作用域(通常是单例singleton,也可以是ptototype、request和session)。

  • type:: Bean 的类型。

使用 Actuator关闭应用程序

当需要关闭某个应用程序时,只需要通过Actuator 发送一一个 POST请求“/shutdown".很显然,关闭程序是一件非常危险的事,所以默认的情况下关闭应该程序的API 接口没有开启的。通过Curl模拟关闭应用程序的请求,Curl 命令如下:

|$ curl -x POST http://localhost: 9091/shutdown

得到的响应信息如下:

"timestamp": 1493092036024,
"status": 404,
"error": "Not Found",
"message": "NO message available" ,
"path": "/shutdown"

上述信息显示找不到该请求路径,这是因为在默认的情况下这个节点是没有开启的,需要将endpoints. shutdown. enabled改为true.在程序的配置文件pplicationyml中添加如下代码:

endpoints:
shutdown:
enabled: true

加上配置之后,重启Spring Boot 程序,再发送一次POST请求,请求API接口地址http://chlhost:9091/shudown,得到的响应信息如下:

{"message": "Shutting down, bye..."
}

从得到的响应信息可以知道程序已经关闭。另外,Actuator的其他10个API接口为SpringBoot程序的运行状态给开发人员或者运维人员提供了许多有用的信息,这些信息帮助我们更好地了解程序所处的状态,例如稳定性如何、故障点在哪里。在这里就不一一介绍了 ,有兴趣的读者可以对每个API接口逐一了解。

使用shell连接Actuator

通过REST API这种方式,开发人员通过Actuator可以很方便地了解运行中的程序的监控信息。Actuator 也可以通过shell的方式连接。通过shell连接Actuator,需要在工程的pom文件加上shell的起步依赖spring-boot-starter- remote-shell,代码如下:

<dependency>
<groupId>org. springf ramework . boot</groupId>
<artifactId>spring-boot-starter-remote-shell
</artifactId>
</dependency>

在程序的pom文件加上spring-boot-starter remote-shell起步依赖后,启动Spring Boot应用程序,在程序的控制台会输出连接shell 的密码,密码是随机的,每次都不一样,大概格式如下:

Using default password for shell access: 45f1 7018-5839-478e-ala1-06de4cc82d4f

与密码相对应的用户名是user,可以通过远程SSH连接shell,它的端口是2000,这是固定的。如果你是用Mac,这时可以用终端连接shell,在终端输入连接命令,命令如下:

 

连接上 shell 这时可以通过终端查看 Actuator 的各个端点。Sprin Boot 提供了 个特有的 sh ll 命令 如表 4-3 所示。

 

现在以第一- 个命令beans为例来做演示,连接上shell后,在终端输入beans, 终端显示了应用上下文的注册信息,如图4-1所示。

由图4-1可知,beans 命令和通过请求REST API接口“/beans"的结果相同,都是以JSON的数据格式输出了应用上下文的所有bean的信息。其他命令就不一一展示了 。

 

Actuator是Spring Boot 的一个非常 重要的功能,Actuator 为开发人员提供了Spring Boot的运行状态信息,通过Actuator可以查看程序的运行状态的信息。

每天持续更新好文,大家可以转发关注一下~~~~~~~~~~~~~~~~

感谢大家支持!!!