获取SpringBoot配置文件属性值方式
1. 注解方式
@Value
2. Properties的工具类获取方式
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.io.IOException;
import java.util.Properties;
/**
* 配置文件工具类
* @author wyp
*/
@Slf4j
public class PropertiesUtil {
/**
* 读取配置文件
* @param location 配置文件路径
* @return Properties
*/
public static Properties getProperties(String location){
try {
log.info("正在加载配置资源\"{}\"",location);
return PropertiesLoaderUtils.loadProperties(new EncodedResource(new ClassPathResource(location), "utf-8"));
} catch (IOException e) {
log.error("加载配置资源\"{}\"加载失败!",location);
e.printStackTrace();
return null;
}
}
}
在resource目录下创建properties文件夹,新增file-config.properties文件
file.img.suffixList=.jpg,.png,.gif,.jpeg
编写测试类测试:
import cn.xc.util.PropertiesUtil;
import org.junit.jupiter.api.Test;
import java.util.Properties;
public class T {
@Test
void t(){
//加载配置文件
Properties properties = PropertiesUtil.getProperties("properties/file-config.properties");
if (properties != null){
//获取配置文件中属性值
String hello = properties.getProperty("file.img.suffixList");
System.out.println(hello);
}
}
}
运行结果:
16:56:43.181 [main] INFO cn.xc.util.PropertiesUtil - 正在加载配置资源"properties/file-config.properties"
.jpg,.png,.gif,.jpeg
3. JDK自带ResourceBundle类读取配置文件
ResourceBundle类是java提供的一个读取properties文件(配置文件)的一种方法。
资源文件必须在classpath下(resource),如果是web项目需放在WEB-INF\classes\目录下。
application.properties
hello=123abc
ResourceBundleTest.java
import java.util.ResourceBundle;
public class ResourceBundleTest {
public static void main(String[] args) {
//fileName.properties,后缀必须省略
String fileName = "application";
ResourceBundle resourceBundle = ResourceBundle.getBundle(fileName);
System.out.println(resourceBundle.getString("hello"));
//区分大小写
System.out.println(resourceBundle.getString("Hello"));
}
}
运行结果:
123abc
Exception in thread "main" java.util.MissingResourceException: Can't find resource for bundle java.util.PropertyResourceBundle, key Hello
本文介绍了三种在SpringBoot中获取配置文件属性值的方式:1)使用@Value注解;2)通过Properties工具类加载;3)利用JDK的ResourceBundle类。详细步骤和示例代码展示了如何操作,帮助开发者更好地理解和使用配置文件。
3718

被折叠的 条评论
为什么被折叠?



