Spring加载Properties配置文件的三种方式

2021-07-13 04:05

阅读:579

标签:resource   .com   key   span   1.0   忽略   sch   lan   als   

一、通过 context:property-placeholder 标签实现配置文件加载

1) 用法:

1、在spring.xml配置文件中添加标签

context:property-placeholder ignore-unresolvable="true" location="classpath:redis-key.properties"/>

2、在 spring.xml 中使用 配置文件属性:$


property name="url" value="${jdbc.url}" />
property name="username" value="${jdbc.username}" />
property name="password" value="${jdbc.password}" /

3、在java文件中使用:

@Value("${jdbc.url}")  
private  String jdbcUrl; // 注意:这里变量不能定义成static

2) 注意点:踩过的坑

Spring中的xml中使用标签导入配置文件时,想要导入多个properties配置文件,如下:

结果发现不行,第二个配置文件始终读取不到,Spring容器是采用反射扫描的发现机制,通过标签的命名空间实例化实例,当Spring探测到容器中有一个org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的Bean就会停止对剩余PropertyPlaceholderConfigurer的扫描,即只能存在一个实例

 

如果有多个配置文件可以使用 “,” 分隔

context:property-placeholderlocation="classpath:db.properties,classpath:monitor.properties" />

可以使用通配符 *

context:property-placeholderlocation="classpath:*.properties" />

3) 属性用法

ignore-resource-not-found //如果属性文件找不到,是否忽略,默认false,即不忽略,找不到文件并不会抛出异常。 
ignore-unresolvable //是否忽略解析不到的属性,如果不忽略,找不到将抛出异常。但它设置为true的主要原因是:

 

 

二、通过 util:properties 标签实现配置文件加载

1)  用法

 1、用法示例: 在spring.xml配置文件中添加标签

xml version="1.0" encoding="UTF-8"?>
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
util:properties id="jdbc" local-override="true" location="classpath:properties/jdbc.properties"/>

 

 2、在spring.xml 中使用配置文件属性:#


bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    property name="driverClass" value="#{jdbc.driverClass}" />
    property name="jdbcUrl" value="#{jdbc.jdbcUrl}" />
    property name="user" value="#{jdbc.user}" />
    property name="password" value="#{jdbc.password}" />
bean>

 

 3.java文件,让Spring注入从资源文件中读取到的属性的值,,为了简便,把几种注入的方式直接写入到一个文件中进行展示:

@Component  
public class SysConf {  
  
    @Value("#{jdbc.url}")  
    private String url;  
    @Value("#{jdbc}")  
    public void setJdbcConf(Properties jdbc){  
        url= sys.getProperty("url");  
    }  
}  

 注意:这里的#{jdbc} 是与第1步的id="jdbc" 相对应的

 

 三、通过 @PropertySource 注解实现配置文件加载

使用和  context:property-placeholder 差不多

 1、用法示例:在java类文件中使用 PropertySource 注解

@PropertySource(value={"classpath:mail.properties"})
public class ReadProperties {
  @Value(value="${mail.username}")
   private String USER_NAME;
}

 

Spring加载Properties配置文件的三种方式

标签:resource   .com   key   span   1.0   忽略   sch   lan   als   

原文地址:https://www.cnblogs.com/guo-rong/p/9544086.html


评论


亲,登录后才可以留言!