spring项目读取配置文件

时间:2023-12-13 16:44:32

Spring项目在运用中读取配置文件有两种方式:

通过项目的配置文件读取

在spring-context.xml里面加入以下代码

spring项目读取配置文件

在运用到的类里面加入

    @Value("#{configProperties['staticUrl']}")
private String staticUrl;

通过代码读取配置文件

获取的代码

public class ConfigurationUtil {

	/**
* 获取
*
*@param pathUrl 路径 文件所在的路径,前后都不需要加"/"
*@param fileName 文件名称 前面不需要加"/"
*
*@return Properties对象
*/
public static Properties get(String pathUrl, String fileName) {
Properties prop = new Properties();
String path = Thread.currentThread().getContextClassLoader().getResource("/" + pathUrl).getPath();
try {
InputStream is = new FileInputStream(path + "/" + fileName);
prop.load(is);
} catch (Exception e) { }
return prop;
}
}

需要引用的地方

spring项目读取配置文件