广州制作网站平台,定州市建设局网站,wordpress调用文章第一张图片,精美wordpress模板下载前言
在项目启动时#xff0c;需要读取一些业务上大量的配置文件#xff0c;用来初始化数据或者配置设定值等#xff0c;我们都知道使用SpringBoot的ConfigurationProperties注解 application.yml配置可以很方便的读取这些配置#xff0c;并且映射成对象很方便的使用需要读取一些业务上大量的配置文件用来初始化数据或者配置设定值等我们都知道使用SpringBoot的ConfigurationProperties注解 application.yml配置可以很方便的读取这些配置并且映射成对象很方便的使用但是这些配置文件比较多的时候而且不希望与application.yml放在一起那么用SpringBoot如何实现呢。
my-config.yml
my-config:key1: hello方法1 导入配置文件
application.yml中可以导入这些配置文件然后继续使用ConfigurationProperties注解这样做的好处是最简单的而且还可以增加my-conf-profile.yml的文件以达到根据profile切换配置文件的目的
application.yml
spring:config:import: my-config.ymlMyConfig.java
Data
Configuration
ConfigurationProperties(prefixmy-config)
public class MyConfig {private String key1;
}方法2 使用PropertySource注解加载配置文件
MyConfig.java
Data
Configuration
ConfigurationProperties(prefixmy-config)
PropertySource(value classpath:my-config.yml, factory YamlPropertySourceFactory.class)
public class MyConfig {private String key1;
}由于PropertySource注解默认只支持properties格式的配置文件所以要自定义yaml文件读取方式
YamlPropertySourceFactory.java
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;public class YamlPropertySourceFactory implements PropertySourceFactory {Overridepublic PropertySource? createPropertySource(String name, EncodedResource resource) throws IOException {return new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource()).get(0);}
}方法3 使用YamlPropertySourceLoader Binder进行手动绑定
以上方法都会将MyConfig对象注入到Spring容器中去而且配置文件也会在上下文的环境中存在如果不想放入容器或者想对绑定的过程做更定制化的处理比如判断文件修改时间等那么需要手动绑定生成配置对象。
MyConfig.java
Data
public class MyConfig {private String key1;
}BindDemo.java
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;public class BindDemo {public MyConfig getMyConfig() throws IOException {Resource resource new ClassPathResource(my-config.yml);// 查看文件最后修改时间FileTime lastModifiedTime Files.getLastModifiedTime(resource.getFile().toPath());String format lastModifiedTime.toInstant().atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern(yyyy-MM-dd HH:mm:ss));System.out.println(system-dic.yml last modified time: format);ListPropertySource? load new YamlPropertySourceLoader().load(resource.getFilename(), resource);Binder binder new Binder(ConfigurationPropertySource.from(load.get(0)));BindResultDicProperties bind binder.bind(my-config, DicProperties.class);return bind.get();}
}