springboot使用自定义配置文件
来源:互联网 发布:deb ubuntu 安装 编辑:程序博客网 时间:2024/05/17 22:20
由于高版本的springboot去掉了@configurationProperties中的location参数,然后在网上查了一些资料,总结了以下两种方法使用自定义的配置文件:
1. 第一种方法:
参考:https://segmentfault.com/q/1010000006828771?_ea=1144561
(1)在resource目录下创建测试用的yml配置文件
myconfig: test: 123
(2)创建bean文件
@Component//使用@Configuration也可以@ConfigurationProperties(prefix = "myconfig")//前缀@PropertySource(value = "classpath:myconfig.yml")//配置文件路径public class MyConfig { @Value("${test}")//需要使用@value注解来注入,否则是null private String test; public String getTest() { return test; } public void setTest(String test) { this.test = test; }}
注:在网上看到的使用方法中,有很多并没有使用@Value注解,但是在本地测试发现(也尝试了@EnableConfigurationProperties注解,但是并不好用)如果不在属性上使用@value注解,总是null
@SpringBootApplicationpublic class ConfigApplication implements CommandLineRunner{@Autowiredprivate MyConfig myconfig;public static void main(String[] args) {SpringApplication.run(ConfigApplication.class, args);}@Overridepublic void run(String... strings) throws Exception {System.out.println(myconfig.getTest());}}输出:123
2.第二种方法:
来自:github 作者:gabrieledarrigo https://github.com/spring-projects/spring-boot/issues/6726
(1)创建YamlPropertySourceFactory继承PropertySourceFactory
public class YamlPropertySourceFactory implements PropertySourceFactory{ @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { return name != null ? new PropertySourcesLoader().load(resource.getResource(), name, null) : new PropertySourcesLoader().load( resource.getResource(), getNameForResource(resource.getResource()), null); } private static String getNameForResource(Resource resource) { String name = resource.getDescription(); if (!org.springframework.util.StringUtils.hasText(name)) { name = resource.getClass().getSimpleName() + "@" + System.identityHashCode(resource); } return name; }}
(2)指定factory为刚才创建的YamlPropertySourceFactory,用此方法不需要使用@Value即可实现属性的自动注入
@Component@ConfigurationProperties(prefix = "myconfig")@PropertySource(value = "classpath:myconfig.yml",factory=YamlPropertySourceFactory.class)//指定factorypublic class MyConfig { private String test; public String getTest() { return test; } public void setTest(String test) { this.test = test; }}
阅读全文
0 0
- springboot使用自定义配置文件
- springboot读取自定义配置文件
- springboot自定义配置文件
- SpringBoot 读取自定义配置文件
- springboot 自定义配置文件
- 使用SpringBoot加载配置文件
- Springboot配置文件的使用
- springboot 使用外部配置文件
- Springboot 之 自定义配置文件及读取配置文件
- Springboot 之 自定义配置文件及读取配置文件
- Springboot 之 自定义配置文件及读取配置文件
- Springboot 之 自定义配置文件及读取配置文件
- Springboot 之 自定义配置文件及读取配置文件
- Springboot 之 自定义配置文件及读取配置文件
- 2springboot 配置文件使用介绍
- SpringBoot之配置文件及自定义参数
- springboot 1.5.2 自定义的配置文件加载
- SpringBoot自定义配置文件fatjar获取不到解决办法
- 【JAVA并发学习二】Java内存模型
- oracle 数据库
- SDUTOJ-3363 数据结构实验之图论七:驴友计划(Floyd)
- 树莓派DHT22传感器设置
- DB2 插入数据并返回自增长主键
- springboot使用自定义配置文件
- hdu--2222--Keywords Search
- Android VPN编程
- 【HPU1189】Ou à [数学]
- Android--资源混淆工具使用说明
- 前向渲染水效果实现
- BZOJ 1997: [Hnoi2010]Planar 2-sat
- 图像边缘锯齿及处理方法
- Go! Go! Go! 来我的另一个博客