总结一下springboot中获取配置文件的方式
先定义配置文件 application.yml
test:
name: sss
test: aaaaa,bbbbbb,ccccc
test2:
test:
- aaaa
- bbbb
- cccc
springboot 启动类上进行扫描
@SpringBootApplication
@EnableConfigurationProperties
//方式一
//@Import({TestProperties.class})
//方式二
@ConfigurationPropertiesScan(basePackages = {"cn.sunpiaoliang.testproperties"})
public class TestPropertiesApplication {
public static void main(String[] args) {
SpringApplication.run(TestPropertiesApplication.class, args);
}
}
方式三:
还可以通过 @Component
@Component
@ConfigurationProperties(prefix = "test2")
配置类
方式一:
@ConfigurationProperties(prefix = "test")
public class TestProperties extends Properties {
public static final String TEST_PREFIX = "test";
public TestProperties() {
}
public String getName() {
return this.getProperty("name","");
}
public String[] getTest() {
return Optional.ofNullable(this.getProperty("test")).orElse("").split(",");
}
}
方式二:
@ConfigurationProperties(prefix = "test2")
public class Test2Properties {
private String[] test;
public Test2Properties() {
}
public String[] getTest() {
return test;
}
public void setTest(String[] test) {
this.test = test;
}
}
以上都可以通过 @Autowired 的方式进行使用
这里说一下 配置类的 两种方式的区别
1、继承Properties 类 的方式 所有的属性都被装进了 hashtable中 可以通过 get的方式或 getProperty 指定属性名称进行获取,但是数组的话就被拆分成了属性名+index
所以要想通过这种方式进行获取数组需要进行特殊处理
例如
配置文件定义属性的时候 通过 分隔符 进行分割成数组
2、不继承Properties类的方式 需要不断维护 配置类中的属性 及getter 、setter 方法才能进行配置。优点是这种可以直接获取到数组。
网友评论