demo:
user:
name: xiaoming
随便写个类,保证能被Spring自动加载就行
import com.alibaba.fastjson.JSONObject;
import myDemo.utils.PropertiesUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.File;
import java.util.HashMap;
* @author xxx
* @since 2023/1/6 23:03
@Component
public class DemoConfig {
@Value("${demo.user.name}")
private String userName;
static {
File file = new File("src/main/resources/bootstrap.yml");
JSONObject jsonObject = PropertiesUtils.ymlToJsonObject(file);
HashMap<String, Object> demoMap = (HashMap<String, Object>) jsonObject.get("demo");
jsonObject.putAll(demoMap);
HashMap<String, Object> userMap = (HashMap<String, Object>) jsonObject.get("user");
jsonObject.putAll(userMap);
String name = jsonObject.get("name").toString();
System.out.println("name = " + name);
启动后结果如下,通过注入(注入方式获取值不演示了)或非注入方式,均可取到配置文件的值
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.5.14)
2023-01-06 23:04:31.888 INFO 16928 --- [ main] myDemo.DemoApplication : No active profile set, falling back to 1 default profile: "default"
2023-01-06 23:04:32.172 INFO 16928 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=ea23a3d1-12cd-3af4-9164-1f94c57f84d1
2023-01-06 23:04:32.297 INFO 16928 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2023-01-06 23:04:32.297 INFO 16928 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2023-01-06 23:04:32.297 INFO 16928 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.63]
2023-01-06 23:04:32.377 INFO 16928 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2023-01-06 23:04:32.377 INFO 16928 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 489 ms
name = xiaoming
2023-01-06 23:04:32.787 INFO 16928 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2023-01-06 23:04:32.945 INFO 16928 --- [ main] myDemo.DemoApplication : Started DemoApplication in 1.946 seconds (JVM running for 2.466)
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<versi...
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.13.3</version>
</depe
spring boot 推荐使用 yaml 格式语言(yml=yaml)来编写配置文件,从而取代 xml 以及 properties,yaml 语言具有像 json 一样简洁明了的特点,但同时具有能够处理复杂类型数据、文本注释的特点,非常适合作为配置文件使用。
本文介绍一下在实际开发过程中关于 yaml 语言字符串换行的问题。