Spring Boot2 学习笔记之获取配置参数(三)
在 spring boot 中的配置文件有两种形式:
application.properties
和application.yml
推荐使用yml
的格式文件进行配置
大概结构如下:
spring: application: name: ${APP_NAME:unknow_name} devtools: restart: exclude: static/**,public/** enabled: true server: port: ${APP_PORT:8080} storage: local: # 文件存储根目录: root-dir: ${STORAGE_LOCAL_ROOT:D:/storage} # 最大文件大小,默认 1000K: max-size: ${STORAGE_LOCAL_MAX_SIZE:1024000} # 是否允许空文件: allow-empty: false # 允许的文件类型: allow-types: jpg, png, gif
获取配置信息
如何在控制器中获取配置文件中的信息呢?
通过
@Value
注解的方式注入 //通过 value 获取 @Value("${ip}") public String ip;
通过 configuration 获取
首先编写一个configuration
//StorageConfiguration @Data @Configuration @ConfigurationProperties("storage.local") public class StorageConfiguration { private String rootDir; private int maxSize; private boolean allowEmpty; private List<String> allowTypes; }
在控制器中可以使用如下方式获取配置文件
@Autowired StorageConfiguration storageConfig; @GetMapping("get_option") public Map<String,Object> get_option(){ Map<String,Object> map = new HashMap<>(); map.put("allow_types",storageConfig.getAllowTypes()); map.put("max_size",storageConfig.getMaxSize()); map.put("root_dir",storageConfig.getRootDir()); map.put("ip_str",this.ip); return map; }