美文网首页
Spring加载配置文件的方式

Spring加载配置文件的方式

作者: torres1 | 来源:发表于2019-12-13 11:21 被阅读0次

转:https://blog.csdn.net/HaHa_Sir/article/details/79105951

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

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文件中使用:
需开启注解注入:
<context:annotation-config/> 或 <context:component-scan/>

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

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

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

<util:properties id="util_Spring"  local-override="true" location="classpath:jeesite.properties"/>

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

<property name="username" value="#{util_Spring['jdbc.username']}" />
<property name="password" value="#{util_Spring['jdbc.password']}" />

3、在java文件中使用:

@Value(value="#{util_Spring['UTIL_SERVICE_ONE']}")
private String UTIL_SERVICE_ONE;

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

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

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

2、在java文件中使用:

@Value(value="${jdbc.username}")
 private String USER_NAME;

四、通过 PropertyPlaceholderConfigurer 类读取配置文件

1、用法示例:在 spring.xml 中使用 <bean>标签进行配置

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:redis-key.properties</value>
            </list>
        </property>
</bean>

2、 PropertyPlaceholderConfigurer 配置方法,等价于 方式一,用法参考方法一

五、 还可以使用 org.springframework.beans.factory.config.PropertiesFactoryBean 加载,这里不再逐一列举了。

相关文章

网友评论

      本文标题:Spring加载配置文件的方式

      本文链接:https://www.haomeiwen.com/subject/kshfnctx.html