一、.env文件说明
.env 文件是全局默认配置文件。若在环境中已经载入,没有指定环境时先去寻找它。
二、使用步骤
1.下载插件EnvFile
要让IDEA能读取.env 文件并加载运行环境变量,必须下载此插件。
- 点击【File】–>【Settings】–>【Plugins】
- 搜索EnvFile并下载此插件
2.重新启动IDEA
3.创建.env环境配置文
USER_NAME=postgres
PASS_WORD=123456
4.添加.env文件为默认的环境配置文件
- 以spring-boot项目添加为例
- 【Edit Configurations】–>【Spring Boot】–>【SensorLinchenliangApplication】–>【EnvFile】–>【Enable EnvFile】 --> 【+】-- >【 .env file】
- 添加后如图
- springboot中application.yml配置如下
spring:
datasource:
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://localhost:5432/postgres?stringtype=unspecified
username: ${USER_NAME}
password: ${PASS_WORD}
- 普通Java项目,springboot测试类如下添加
5.测试环境
@Test
void getEnv(){
System.out.println(System.getenv("USER_NAME"));
System.out.println(System.getenv("PASS_WORD"));
}