背景
在SpringBoot實際開發中,通常會把一些業務相關的配置檔案單獨寫在一個properties檔案中。在項目測試過程中,項目被打成jar包,部署到Linux系統。由于配置檔案放到resources檔案中,會被打包進jar包,如果修改配置檔案,每次都需要重新打包。為了友善不用你每次改配置檔案都重新打包一次,我們通常會将配置檔案放到工程外部的檔案夾中。那麼如何加載外部配置檔案?

解決方案:
步驟一:
在resources檔案夾下建立一個spring的配置檔案
配置檔案内容:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
<!--配置檔案導入-->
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="fileEncoding" value="utf-8"/>
<property name="locations">
<list>
<value>file:config/source.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
</beans>
步驟二:導入spring配置檔案
@SpringBootApplication
// 導入spring配置檔案
@ImportResource({"classpath:spring/applicationContext.xml"})
public class SpringbootMvc01Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootMvc01Application.class, args);
}
}
測試:
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootMvc01ApplicationTests {
@Value("${name}")
private String name;
@Test
public void test() {
System.out.println(name);
}
}