创建application.properties
com.app.title=app title
com.app.description=this is a app
创建配置类
prefix = “com.app” 对应到配置文件中。@Data是lombok组件使用的声明,用来省略get/set函数。
@Component
@Data
@ConfigurationProperties(prefix = "com.app")
public class AppProperties {
private String title;
private String description;
}
修改入口类
增加以下注解,对应配置类类名
@EnableConfigurationProperties({AppProperties.class})
调用
注意AppProperties appProperties;对象名必须是类名并首字母小写,否则会报错。
@RestController
public class HelloWorldController {
@Autowired // 声明
AppProperties appProperties; // 声明
@RequestMapping("/hello3")
public Map<String,String> index3() {
System.out.println(appProperties.getTitle()); // 调用
System.out.println(appProperties.getDescription()); // 调用
Map<String,String> map = new HashMap<String,String>();
map.put("code","1");
map.put("msg","hello world");
return map;
}
}
参考文档
https://www.cnblogs.com/shamo89/p/8178109.html
包含以下内容:
- 多种配置引用方式
- 参数间引用
- 自定义配置文件
- 随机值配置
- 外部配置
- 配置文件优先级
- 多环境配置