Spring—@PropertySource读取properties配置文件属性

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]

猜你喜欢

转载自blog.csdn.net/weixin_38772170/article/details/84064969