Spring—@PropertySource讀取properties配置檔案屬性
阿新 • • 發佈:2018-11-15
1、示例程式碼Controller層
@Controller @RequestMapping("/test") @PropertySource("classpath:application.properties") public class TestController { @Value("${name}") private String name; @RequestMapping("/string") //返回字串 @ResponseBody public String rest() { return getName(); } }
2、示例程式碼配置檔案:application.properties
name=${random.value}
age=12
3、注意事項
@PropertySource:需加classpath指定配置檔案路徑,否則專案打war/jar包會拋異常
java.lang.IllegalStateException: Failed to load ApplicationContext
nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/application.properties]
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/application.properties]