java 读取配置文件
引入的jar文件
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
代码块: PropertiesUtil.java
package com.example.demo.util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
/** * @description: 读取配置文件工具类 * @create: 2020/03/15 09:41 **/
public class PropertiesUtil {
private static Logger log = LoggerFactory.getLogger(PropertiesUtil.class);
private static Properties props;
static{
String filename = "application.properties";
props = new Properties();
try {
props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(filename),"UTF-8"));
} catch (IOException e) {
log.error("配置文件读取异常",e);
}
}
public static String getProperty(String key){
String value = props.getProperty(key.trim());
if(StringUtils.isBlank(value)){
return null;
}
return value;
}
/** * 使用场景:如果忘记在配置文件中配置key,那么也不会取到null值,因为我们有个兜底的,传入了默认值value * @param key * @param defaultValue * @return */
public static String getProperty(String key, String defaultValue){
String value = props.getProperty(key.trim());
if(StringUtils.isBlank(value)){
value = defaultValue;
}
return value;
}
}
PropertiesUtil.java的使用解释:
- PropertiesUtil的实现要在tomcat启动的时候就要读取到application.properties里面的配置,所以需要使用static块来解决这类问题。
- 执行顺序:static块优于普通代码块,普通代码块优于构造代码块。static块只执行一次。在类被加载的时候执行且仅会执行一次。一般都用static块做初始化静态变量。类被java的class loader【类加载器】加载到jvm里,然后static里面的代码会被执行且只执行一次。构造代码块在构造对象的时候每次都会执行
- key.trim()的作用,去掉前后空格。避免配置文件中这种等号后面有空格的写法:server.servlet.context-path = /demo
配置文件application.properties
server.servlet.context-path=/demo
# 8080前后有空格,获取到这个值需要用trim()去前后空格
server.port = 8080
代码块:测试获取配置文件中的配置
package com.example.demo;
import com.example.demo.util.PropertiesUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
public class DemoApplication {
@RequestMapping("/hello")
public void hello(){
String value = PropertiesUtil.getProperty("name","刘德华");
System.out.println("配置文件没有配置的key=" + value);
value = PropertiesUtil.getProperty("server.servlet.context-path");
System.out.println("配置文件配置的key=" + value);
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
启动项目并且访问localhost:8080/demo/hello
,访问结果
配置文件没有配置的key=刘德华
配置文件配置的key=/demo
还没有评论,来说两句吧...