走进 Spring Boot 第一步之 Java Properties 类
Java Spring Boot About 2,331 words配置文件
Spring Boot启动第一步将会加载spring.factories
配置文件中的类,通过ClassLoader
加载Properties
。
# Application Context Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
org.springframework.boot.context.ContextIdApplicationContextInitializer,\
org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\
org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer
类解读
wiki
中的示例
# You are reading the ".properties" entry.
! The exclamation mark can also mark text as comments.
# The key and element characters #, !, =, and : are written with
# a preceding backslash to ensure that they are properly loaded.
website = http\://en.wikipedia.org/
language = English
# The backslash below tells the application to continue reading
# the value onto the next line.
message = Welcome to \
Wikipedia\!
# Add spaces to the key
key\ with\ spaces = This is the value that could be looked up with the key "key with spaces".
# Unicode
tab : \u0009
- 一行中的第一个非空白字符是
#
/!
则该行表示注释,不会被读取; - 使用
key=value
/key:value
/key value
三种方式表示键值对; - 反斜杠
\
用于转义#
/!
/:
/=
这四个字符; - 反斜杠
\
在一行的末尾则表示继续读取下一行(拼接下一行使value
成为一行); - 中文将转为
unicode
编码;
代码
写入
Properties p = new Properties();
p.setProperty("name", "zhangsan");
p.setProperty("age", "25");
p.setProperty("birthday", "20180815");
p.setProperty("hobby", "abc,edf");
p.store(Files.newOutputStream(Paths.get("test.txt"), StandardOpenOption.CREATE), "This is comments");
文件内容
#This is comments
#Thu Apr 02 17:30:24 CST 2020
age=25
name=zhangsan
hobby=abc,edf
birthday=20180815
读取
Properties properties = new Properties();
properties.load(Files.newInputStream(Paths.get("test.txt")));
properties.list(System.out);
输出
-- listing properties --
age=25
name=zhangsan
hobby=abc,def
birthday=20180815
读取resource下配置文件
注意配置文件需放置在resource
资源文件夹下,若出现空指针,maven
项目查看是否build
过项目,在target/classes
是否存在文件,Gradle
项目类同。
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("test.txt");
UrlResource resource = new UrlResource(url);//url注意空指针,示例代码未判空
Properties properties = new Properties();
properties.load(resource.getInputStream());
参考
https://zh.wikipedia.org/wiki/.properties
https://docs.oracle.com/javase/7/docs/api/java/util/Properties.html#load(java.io.Reader)
Views: 2,994 · Posted: 2020-04-03
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...