在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;
親測可用。