Spring加载Properties配置文件的几种方式
2023-09-11 14:19:38 时间
一:通过context:property-placeholder标签实现配置文件加载
在spring的配置文件中添加如下声明
<context:property-placeholder ignore-unresolvable="true" location="classpath:jdbc.properties"/>
引用值时,注意使用$引用需要的值
1.在datasource.xml中
<!-- 配置数据源 --> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" />
2.在java代码中
@Value("${targetVal}") private String targetVal; // 注意:这里变量不能定义成static
二:通过 util:properties 标签实现配置文件加载
在spring的配置文件中添加如下声明
<util:properties id="jdbc" local-override="true" location="classpath:jdbc.properties"/>
需要注意几点,这种方式需要在spring配置文件头部进行如下声明
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"
在引用值时,注意使用#
1.在xml中使用
<property name="username" value="#{jdbc['jdbc.username']}" /> <property name="password" value="#{jdbc['jdbc.password']}" />
2.在java代码中
@Value(value="#{jdbc['targetVal']}") private String targetVal;
三、通过 @PropertySource 注解实现配置文件加载
在java类文件中使用 PropertySource 注解:
@PropertySource(value={"classpath:jdbc.properties"}) public class ReadProperties { @Value(value="${jdbc.username}") private String username; }
四、通过 PropertyPlaceholderConfigurer 类读取配置文件
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>/WEB-INF/mail.properties</value> <value>classpath:jdbc.properties</value> </list> </property> </bean>
取值与方法一相同
五:使用 PropertiesFactoryBean 加载
<bean id="propertiesReader" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath*:/conf/application.properties</value> <value>classpath*:/conf/streamserver.properties</value> </list> </property> </bean>
取值与方法二相同
以上是常见的取值方式,下一篇将会介绍context:property-placeholder常用的属性
转 : https://blog.csdn.net/Cool_Coding/article/details/90617687
相关文章
- spring boot 引用外部配置文件
- spring boot: spring Aware的目的是为了让Bean获得Spring容器的服务
- [Spring boot] Configuring and Accessing a Data Source
- Spring配置文件总结
- Redis+Spring缓存实例(windows环境,附实例源码及详解)
- 监听器如何获取Spring配置文件
- Spring注解方式配置切面类
- Spring学习10- bean的生命周期(阿里面试题目两次面试均提到)
- Spring Boot:定制PropertyEditors
- Atitit spring单元测试 注解 获取服务名 Spring文件单独放在一个文件夹,去掉dubbo配置,方便测试 里面包含的mybatis 找不到,只好设置成相对于class绝对路径可以了
- spring schedule定时任务(二):配置文件的方式
- 学习Spring Boot:(十四)spring-shiro的密码加密
- 学习Spring Boot:(一)入门
- Maven 多环境指定 Profile 环境编译打包 & Spring Boot 动态选择配置文件
- spring boot 启动错误:Could not resolve placeholder
- Spring JDBC插入数据
- 服务降级是什么?Spring Cloud如何实现?
- 【Spring源码学习】spring IOC容器管理