使用spring的org.springframework.beans.factory.config.PropertyPlaceholderConfigurer类加载Properties配置文件,通过源码可以知道,默认加载的是classpath下的文件,配置如下:
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:config/init.properties</value>
</property>
</bean>
如果有多个配置文件加载,则:
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config/init.properties</value>
<value>classpath:config/init.properties</value>
</list>
</property>
</bean>
这样spring就能够加载properties文件了。
配置文件位于外部目录
但是对于外部目录的配置文件,使用org.springframework.beans.factory.config.PropertyPlaceholderConfigurer也是可以加载的,不过要修改他的路径配置方式,如下:
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>file:${user.dir}/config/init.properties</value>
<value>file:${user.dir}/config/init2.properties</value>
</list>
</property>
</bean>
这样就可以成功加载外部目录的配置文件了,${user.dir}是系统变量,指用户当前目录所在。
代码中加载配置文件
应该某些需求,配置文件得从java代码是加载,这里我就说一样代码中加载外部目录的配置文件的方式,加载classpath目录下的配置文件这里就不再多说了,相
信网上有太多较好的简答。如下代码:
private static final Properties sysConfig = new Properties();
static {
try {
InputStream iStream = new FileInputStream(new File("config", "shellConfig.properties"));
sysConfig.load(iStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getPropertyValue(String key){
return sysConfig.getProperty(key);
}
相关推荐
本文档是很专业的 Spring动态加载配置文件,实现热部署方案。
Spring3.0 配置文件中加载Properties文件的小例子
本文档介绍了spring中的在classpath中加载配置文件
在spring中加载多个配置文件的方法,希望对你有用。
本文详细介绍了Spring中如何加载多个配置文件
Spring 加载多个配置文件
主要给大家介绍了关于Spring Boot加载配置文件的完整步骤,文中通过示例代码介绍的非常详细,对大家的学习或者使用Spring Boot具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
springmvc项目中如何加载jar包中的spring配置文件
主要介绍了浅谈SpringBoot2.4 配置文件加载机制大变化,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
可以从Jar外部加载JDBC.properties的Spring-mybatis配置文件,直接可以用,适合部署可执行jar时,从外部配置数据库
加载spring 文件,在web.xml中的配置
主要介绍了spring如何加载配置多个配置文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
spring boot中配置mybatis xml资源文件热加载的方法以及相关文件
spring boot中配置mybatis xml资源文件热加载的方法以及相关文件
在web应用用写的一些Socket服务等,需要配置IP、端口等信息,我们希望这些信息写到配置文件中,并有spring帮我们加载。
加载spring配置文件,提供getBean接口.
主要介绍了详解Spring加载Properties配置文件的四种方式,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
spring 启动时根据配置文件的不同加载不同的文件