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]