Spring Boot 中如何在resource中自定义一个yaml文件,并加载到项目中呢?
今天在SpringBoot项目中需自定义一个yaml,那么如何将这个文件加入到SpringBoot中呢?下文笔者将一一道来,如下所示
1.在resource下定义一个yaml文件 2.编写一个配置类,加载yaml文件即可例:将test.yaml加载到SpringBoot中
SpringBootConfiguration.java
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
/**
* @author java265.com
*/
@Configuration
public class SpringBootConfiguration {
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
// 加载YML格式自定义配置文件 这里的 front.yml 为你新建的放在根目录下的 yml文件名称
yaml.setResources(new ClassPathResource("test.yml"));
configurer.setProperties(yaml.getObject());
return configurer;
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


