java – 加载多个YAML文件(使用@ConfigurationProperties?)
使用
Spring Boot 1.3.0.RELEASE
我有几个yaml文件描述了程序的几个实例.我现在想要将所有这些文件解析为List< Program> (Map,无论如何),所以我稍后可以在所有程序中搜索给定条件的最合适的实例. 我非常喜欢使用@ConfigurationProperties的方法,它对于单个yaml文件工作得很好,但我还没有找到使用该方法读取目录中所有文件的方法. 当前的方法适用于单个文件: programs/program1.yml name: Program 1 minDays: 4 maxDays: 6 可以阅读 @Configuration @ConfigurationProperties(locations = "classpath:programs/program1.yml",ignoreUnknownFields = false) public class ProgramProperties { private Program test; //Program is a POJO with all the fields in the yml. //getters+setters 我尝试将位置更改为列出所有文件位置的数组= {“classpath:programs / program1.yml”,“classpath:programs / program2.yml”}以及使用locations =“classpath:programs / *.yml “,但仍然只加载第一个文件(数组方法)或根本不加载(通配符方法). 所以,我的问题是,Spring Boot中最好的方法是在classpath目录中加载一堆yaml文件并将它们解析为(List of)POJO,这样它们可以在Controller中自动装配?我是否需要直接使用Snakeyaml,还是有一种我还没有找到的集成机制? 编辑: private static final Yaml yaml = new Yaml(new Constructor(Program.class)); private static final ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); try { for (Resource resource : resolver.getResources("/programs/*.yml")) { Object data = yaml.load(resource.getInputStream()); programList.add((Program) data); } } catch (IOException ioe) { logger.error("failed to load resource",ioe); } 解决方法
就我理解你的问题而言,我目前正在做的事情几乎是一样的.
我有一个application.yml以及特定于配置文件的yml文件,例如我的src / main / resources中的application- {profile} .yml. 在application.yml中,我定义了默认的配置文件键值,它们被特定于配置文件的yml文件部分覆盖. 如果您希望对YML键/值进行类型安全且定义良好的访问,则可以使用以下方法: @ConfigurationProperties public class AppSettings { String name; // has to be the same as the key in your yml file // setters/getters } 在Spring-Boot配置中,您必须在配置类中添加以下注释: @ComponentScan @EnableAutoConfiguration @EnableConfigurationProperties( value = { AppSettings.class,SomeOtherSettings.class } ) public class SpringContextConfig { @Autowired private AppSettings appSettings; public void test() { System.out.println(appSettings.getName()); } } @Autowiring也可以从其他豆子访问. 以简短的方式将它们结合在一起:是的,可以通过Spring-profiles为您的应用程序使用多个YAML文件.您可以通过命令args,以编程方式或通过系统env(SPRING_PROFILES_ACTIVE = name1,name2)定义当前的活动弹簧配置文件.因此,每个配置文件可以有几个application.yml文件(参见上文). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |