走进Spring Boot第一步之Java Properties类

JavaSpring Boot大约 2330 字

配置文件

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)

阅读 133 · 发布于 2020-04-03

————        END        ————

扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看换一批