美文网首页
SpringBoot Yaml初始化器

SpringBoot Yaml初始化器

作者: htger | 来源:发表于2020-09-25 16:30 被阅读0次

官方注解 @PropertySource 仅支持加载 .properties 配置文件,不能加载 .yml。这样,不方便调试本地测试代码(需要额外写配置数据库、ES等代码)。
下面主要介绍如何在单元测试不使用注解 @SpringbootTest 加载 yml配置的方法。

配置文件

  • yml 配置文件


    es配置片段
  • 自定义的 elasticsearch Java 配置

@Configuration
@ConfigurationProperties(prefix = "custom.es")
@Data
public class ElasticsearchConfig {

    private String clusterName;
    /*host:port*/
    private List<String> nodes;
    private String auth;

    @Bean
    public TransportClient transportClient() throws UnknownHostException {
        Settings settings = Settings.builder()
                .put("cluster.name", clusterName)
                .put("xpack.security.user", auth)
                .put("client.transport.sniff", false)
                .build();
        TransportClient client = new PreBuiltXPackTransportClient(settings);
        if (CollectionUtils.isEmpty(nodes)) {
            throw new UnknownHostException();
        }
        for (String node : nodes) {
            String[] addressArr = node.split(":");
            client.addTransportAddress(
                    new InetSocketTransportAddress(InetAddress.getByName(addressArr[0]), Integer.parseInt(addressArr[1])));
        }
        return client;
    }

    @Bean
    public AdminClient adminClient(TransportClient transportClient) {
        return transportClient.admin();
    }
}

测试用例,引入ConfigFileApplicationContextInitializer

  • 加入 ConfigFileApplicationContextInitializer 到上下文,加载yml配置文件
@RunWith(SpringRunner.class)
@Import(ElasticSearchTest.Config.class)
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
public class ElasticSearchTest {

    @TestConfiguration
    @Import(ElasticsearchConfig.class)
    @EnableConfigurationProperties
    public static class Config {
        @Bean
        ElasticSearchIndexDao elasticSearchIndexDao(TransportClient client) {
            return new ElasticSearchIndexDaoImpl(client);
        }
    }
}

注:我的springboot是2.x版本

相关文章

网友评论

      本文标题:SpringBoot Yaml初始化器

      本文链接:https://www.haomeiwen.com/subject/kbufuktx.html