springboot之加载配置文件

本文介绍了SpringBoot中配置文件的加载机制,包括加载配置文件的代码位置、加载方式及目录,支持的文件格式如XML、YML和properties等,并强调了加载YML文件时对snakeyaml包的依赖。

1,springboot加载配置文件的代码在。

    1,ConfigFileApplicationListener的loadIntoGroup方法

    2,加载方式有file,classpath。加载目录也多种。详情请 自己dibug

    3,加载文件格式有 xml。yml,与 pro

    ,4,加载 yml文件,必须依赖  snakeyaml 包,没有snakeyaml包,是无法加载 yml配置文件的

Spring Boot可以通过多种方式加载配置文件,包括: 1. application.properties/application.yml文件:Spring Boot会自动加载classpath下的这两个文件,可以在其中定义应用程序的配置属性。 2. @PropertySource注解:可以通过该注解指定要加载配置文件,例如: @SpringBootApplication @PropertySource("classpath:myconfig.properties") public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } 3. Environment接口:可以通过该接口获取配置属性的值,例如: @Autowired private Environment env; String value = env.getProperty("my.property"); 4. 自定义配置文件:可以通过实现org.springframework.boot.env.PropertySourceLoader接口来加载自定义的配置文件,例如: public class MyPropertySourceLoader implements PropertySourceLoader { @Override public String[] getFileExtensions() { return new String[] { "myconfig" }; } @Override public PropertySource<?> load(String name, Resource resource, String profile) throws IOException { Properties props = new Properties(); props.load(resource.getInputStream()); return new PropertiesPropertySource(name, props); } } 然后在application.properties/application.yml中添加以下配置: spring.profiles.active=myprofile spring.config.name=myconfig spring.config.location=classpath:/,classpath:/config/ 这样就可以在classpath:/或classpath:/config/目录下加载myconfig.myprofile文件了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值