springboot配置文件可以是properties,也可以是yml类型,它们都支持字符型,也支持列表list类型,假定在yml配置文件中支持列表类型格式如下:
application.yml
demo:
type:
code:
- 200
- 201
- 300
- 400
- 501
编写对应的java类
package com.xxx.mongodemo.config;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "demo.type")
public class TypeCodeConfig {
private List code;
public void setCode(List code) {
this.code = code;
}
public List getCode() {
return code;
}
}
在其他地方使用:
package com.xxx.mongodemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.xxx.mongodemo.config.TypeCodeConfig;
@SpringBootApplication
public class App implements CommandLineRunner{
public static void main( String[] args ){
SpringApplication.run(App.class, args);
}
@Autowired
private TypeCodeConfig config ;
@Override
public void run(String... args) throws Exception {
System.out.println(config.getCode());
}
}
这里直接在启动类中读取这个list,这里需要注意,使用yml中配置的list需要先将对象注入,然后通过get方法读取它的值。
打印信息如下所示,正确读取了list的值:
2021-04-14 14:17:41.292 INFO 16140 --- [ main] com.xxx.mongodemo.App : Started App in 2.059 seconds (JVM running for 2.396)
[200, 201, 300, 400, 501]
有的地方直接通过数组(String[])去接收,而不是使用的是List
这里总结一些特别的地方:
1、list类型的yml配置文件中,需要使用"-"来组成一个列表集合。
2、yml中的前缀没有层级限制,如果是多层级,比如这里的demo/code,在java类中配置ConfigurationProperties注解的prefix就写作"demo.code"
3、属性名称在yml文件中支持连字符"-",比如four-span,在java类中配置属性就需要转为驼峰式,fourSpan。
4、java类属性需要配置set,get方法。