1. Spring基於xml加載和讀取properties文件配置


在src目錄下,新建test.properties配置文件,內容如下

name=root
password=123456
logArchiveCron=0/5 * * * * ? 

一種是使用spring提供的一個標簽,在spring-config.xml中配置單個properties,如下

<context:property-placeholder location="classpath:test.properties"/>

配置多個properties通過分號隔開在后面添加即可,例如

<context:property-placeholder location="classpath:test.properties,classpath:jdbc.properties"/>

另一種是通過注到bean的屬性來進行配置,這里也是配置多個,如下

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

取值方式如下:

在spring-config.xml中獲取properties文件中的值:

<task:scheduled-tasks>
  <task:scheduled ref="testJob" method="logArchiveBak" cron="${logArchiveCron}" />
</task:scheduled-tasks>

在java類里面獲取properties文件里面的值,通過注解@value(${key})來獲取

@Value("${name}")
private String name;
@Value("${password}")
private String password;
親測可用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM