SpringBoot进阶教程 | 第一篇:YML多文档块实现多环境配置

你是否为SpringBoot一个功能多个yml和多个properties文件区分不同运行环境配置,经常为这些配置文件的管理而头疼,现在通过这篇文章,将彻底解决你的烦恼,这篇文篇介绍,怎么通过yml文件构建多文档块,区分不同环境配置,自由切换不同环境启动项目,一个配置文件搞定。

YAML简介

YAMLYAML不是一种标记语言的外语缩写(见前方参考资料原文内容);但为了强调这种语言以数据做为中心,而不是以置标语言为重点,而用返璞词重新命名。它是一种直观的能够被电脑识别的数据序列化格式,是一个可读性高并且容易被人类阅读,容易和脚本语言交互,用来表达资料序列的编程语言。

它是类似于标准通用标记语言的子集XML数据描述语言,语法比XML简单很多。

基本语法结构

多行缩进

数据结构可以用类似大纲的缩排方式呈现,结构通过缩进来表示,连续的项目通过减号“-”来表示,map结构里面的key/value对用冒号“:”来分隔。样例如下:

house:
  family:
    name: Doe
    parents:
      - John
      - Jane
    children:
      - Paul
      - Mark
      - Simone
  address:
    number: 34
    street: Main Street
    city: Nowheretown
    zipcode: 12345

注意:

1.字串不一定要用双引号标识;

2.在缩排中空白字符的数目并不是非常重要,只要相同阶层的元素左侧对齐就可以了(不过不能使用`TAB`字符);

3.允许在文件中加入选择性的空行,以增加可读性;

4. 在一个档案中,可同时包含多个文件,并用`“——”`分隔;

5.选择性的符号`“...”`可以用来表示档案结尾(在利用串流的通讯中,这非常有用,可以在不关闭串流的情况下,发送结束讯号)。

单行缩写

YAML也有用来描述好几行相同结构的数据的缩写语法,数组用'[]'包括起来,hash'{}'来包括。因此,上面的这个YAML能够缩写成这样:

house:
  family: { name: Doe, parents: [John, Jane], children: [Paul, Mark, Simone] }
  address: { number: 34, street: Main Street, city: Nowheretown, zipcode: 12345 }

准备工作

环境:

windows
jdk 8
maven 3.0
IDEA

构建工程

 <?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>
	<parent>
		<groupId>cn.zhangbox</groupId>
		<artifactId>spring-boot-study</artifactId>
		<version>1.0-SNAPSHOT</version>
	</parent>

	<groupId>cn.zhangbox</groupId>
	<artifactId>spring-boot-02-config</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>spring-boot-02-config</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<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-configuration-processor</artifactId>
			<optional>true</optional>
		</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>

修改YML配置

#选择哪一个环境的配置
#这里可以在每个环境配置redis,数据库(mysql),消息(kafka)等相关的组件的配置
spring:
  profiles:
    active: prod

#文档块区分为三个---
---
server:
  port: 8081
spring:
  profiles: test

#文档块区分为三个---
---
server:
  port: 8082
spring:
  profiles: test

#文档块区分为三个---
---
server:
  port: 8083
spring:
  profiles: prod

创建启动类

@SpringBootApplication
public class SpringBootConfigApplication {

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

控制台打印

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.9.RELEASE)

2018-07-04 15:07:26.214  INFO 14812 --- [           main] c.z.s.SpringBootConfigApplication        : Starting SpringBootConfigApplication on MS-20180428GSYE with PID 14812 (C:\Users\Administrator\Desktop\spring-boot-02-config\target\classes started by Administrator in C:\Users\Administrator\Desktop\spring-boot-02-config)
2018-07-04 15:07:26.219  INFO 14812 --- [           main] c.z.s.SpringBootConfigApplication        : The following profiles are active: prod
2018-07-04 15:07:26.281  INFO 14812 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3f57bcad: startup date [Wed Jul 04 15:07:26 GMT+08:00 2018]; root of context hierarchy
2018-07-04 15:07:28.988  INFO 14812 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8083 (http)
2018-07-04 15:07:29.029  INFO 14812 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-07-04 15:07:29.031  INFO 14812 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.23
2018-07-04 15:07:29.184  INFO 14812 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-07-04 15:07:29.184  INFO 14812 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2909 ms
2018-07-04 15:07:29.419  INFO 14812 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2018-07-04 15:07:29.424  INFO 14812 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-07-04 15:07:29.424  INFO 14812 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-07-04 15:07:29.424  INFO 14812 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-07-04 15:07:29.424  INFO 14812 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-07-04 15:07:30.605  INFO 14812 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3f57bcad: startup date [Wed Jul 04 15:07:26 GMT+08:00 2018]; root of context hierarchy
2018-07-04 15:07:30.731  INFO 14812 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-07-04 15:07:30.732  INFO 14812 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-07-04 15:07:30.777  INFO 14812 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-04 15:07:30.777  INFO 14812 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-04 15:07:30.833  INFO 14812 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-04 15:07:31.166  INFO 14812 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-07-04 15:07:31.470  INFO 14812 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8083 (http)
2018-07-04 15:07:31.475  INFO 14812 --- [           main] c.z.s.SpringBootConfigApplication        : Started SpringBootConfigApplication in 5.897 seconds (JVM running for 7.324)

至此YML多文档块多环境配置是不是非常简单,切换环境只需要修改

spring:
  profiles:
    active: prod

中active对应的环境的值即可。

源码地址

Spring Boot多文档块多数据源源码

写在最后

欢迎关注喜欢、和点赞后续将推出更多的SpringBoot教程,敬请期待。 欢迎关注我的微信公众号获取更多更全的学习资源,视频资料,技术干货! 欢迎扫码关注

公众号回复“学习”,拉你进程序员技术讨论群干货资源第一时间分享。

公众号回复“视频”,领取800GJava视频学习资源。 java学习全套820G资源

公众号回复“全栈”,领取1T前端Java产品经理微信小程序Python等资源合集大放送。 全栈资料javapython机器学习产品经理接近1T资源

公众号回复“慕课”,领取1T慕课实战学习资源。 慕课实战大全phppython测试后端前端前端微信1061G资源

公众号回复“实战”,领取750G项目实战学习资源。 前后端实战项目750实战资源

公众号回复“面试”,领取8G面试实战学习资源。 JAVA面试实战视频传智面试讲解8G面试资源

转载于:https://my.oschina.net/u/3529959/blog/3040179

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中,可以使用多个配置文件来实现环境配置。首先,需要创建多个配置文件,例如application-dev.yml(开发环境)、application-prod.yml(生产环境)、application-test.yml(测试环境)。 然后,可以通过指定启动参数来选择使用不同的配置文件。比如,在测试环境中可以使用以下命令启动应用程序:java -jar 项目.jar --spring.profiles.active=test。在生产环境中可以使用以下命令启动应用程序:java -jar 项目.jar --spring.profiles.active=prod。这种方式可以灵活地选择使用不同的配置文件。 另一种方式是在pom.xml文件中指定环境配置。具体来说,可以在application.yml中选择需要使用的配置文件。可以通过在application.yml文件中的spring.profiles.active属性来指定需要使用的配置文件的后缀。例如,如果要使用开发环境配置,可以将spring.profiles.active设置为dev。 无论使用哪种方式,都需要在配置文件中指定相应环境下的配置内容。例如,在dev配置文件中可以设置数据库的URL、用户名、密码以及服务器端口。类似地,在test和prod配置文件中也可以设置相应环境配置。 总之,通过创建多个配置文件,并通过指定启动参数或在配置文件中指定需要使用的配置,可以实现Spring Boot的多环境配置。这样可以在不同的环境中灵活地配置应用程序所需的参数,避免重复配置的情况。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值