网站首页 > 精选教程 正文
前言
一般我们的配置信息默认都是会配置在/src/main/resources/application.properties(或者application.yml)文件中,当然,也可以在resources文件夹下添加自己的配置文件,甚至子目录中添加自己的配置文件,那么我们又该如何读取自己添加的配置文件中的内容呢?
准备
我们先定义一个公共的输出配置信息的方法如下:
private static void getProperties(InputStream inputStream) {
Properties properties = new Properties();
if (inputStream == null) {
return;
}
try {
properties.load(inputStream);
properties.list(System.out);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这里是通过java.util下的Properties类来获取配置文件中的属性
添加自定义的配置文件,在resources目录下添加子目录config并添加配置文件db.properties
内容如下:
jdbc.driver=com.mysql.cj.jdbc.Driver
在java中,resources文件夹下的文件在编译后,都是为根目录(classpath)。接下来,准备采用以下的6种方式进行配置内容的读取
六种方式
- 方法一
URL path = this.getClass().getClassLoader().getResource("config/db.properties"); // 注意路径不带/开头
getProperties(path.openStream());
- 方法二
URL path = this.getClass().getResource("/config/db.properties"); //路径需要以/开头
getProperties(path.openStream());
- 方法三
在springboot项目我还可以使用如下的方式:
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/db.properties");//与方法一类似,只不过直接返回了InputStream类型
getProperties(inputStream);
- 方法四
springboot项目中使用
inputStream = this.getClass().getResourceAsStream("/config/db.properties");//与方法二类似,只不过返回了InputStream类型了
getProperties(inputStream);
- 方法五
springboot项目中使用
ClassPathResource classPathResource = new ClassPathResource("config/db.properties");
getProperties(classPathResource.getInputStream());
- 方法六
springboot项目中使用,通过@Value注解,但是我们还需要通过@PropertySource("classpath:config/db.properties")
注解指定配置文件的路径,如果是默认的配置文件,如:application.properties(.yml)就不需要指定路径
@SpringBootApplication
@PropertySource("classpath:config/db.properties")
public class App implements CommandLineRunner{...}
@Value("${jdbc.driver}")
private String driver;
通过上述6种方法都可以成功获取到自定义配置文件中的配置信息,如果大家还有更好的方式,可以评论区留言。
猜你喜欢
- 2024-12-01 从零学大数据之Java篇第二十五章:文件操作详解
- 2024-12-01 Java中读取File文件内容转为String类型
- 2024-12-01 JAVA文件基本操作
- 2024-12-01 Java如何获取一个文本文件的编码(格式)信息呢?
- 2024-12-01 会用Java读取文本文件就够了吗?文件超大怎么办?
- 2024-12-01 灵魂一问:一个Java文件的执行全部过程你确定都清楚吗?
- 2024-12-01 读取Spring配置文件的方法(Spring读取资源文件)
- 2024-12-01 JAVA中的文件操作2-如何读写文件
- 2024-12-01 Java高效读取纯文本文件
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- nginx反向代理 (57)
- nginx日志 (56)
- nginx限制ip访问 (62)
- mac安装nginx (55)
- java和mysql (59)
- java中final (62)
- win10安装java (72)
- java启动参数 (64)
- java链表反转 (64)
- 字符串反转java (72)
- java逻辑运算符 (59)
- java 请求url (65)
- java信号量 (57)
- java定义枚举 (59)
- java字符串压缩 (56)
- java中的反射 (59)
- java 三维数组 (55)
- java插入排序 (68)
- java线程的状态 (62)
- java异步调用 (55)
- java中的异常处理 (62)
- java锁机制 (54)
- java静态内部类 (55)
- java怎么添加图片 (60)
- java 权限框架 (55)
本文暂时没有评论,来添加一个吧(●'◡'●)