java 属性自定义配置_java – Spring Boot:自定义属性配置和测试

我正在使用Spring Boot 2.0和默认的application.yml属性文件.我想将它拆分为单独的属性文件,因为它变得很大.

此外,我想编写测试来检查属性的正确性:将出现在生产应用程序上下文中的值(而不是测试中的值).

这是我的属性文件:src / main / resources / config / custom.yml

my-property:

value: 'test'

物业类:

import lombok.Data;

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.PropertySource;

@Data

@Configuration

@ConfigurationProperties(prefix = "my-property")

@PropertySource("classpath:config/custom.yml")

public class MyProperty {

private String value;

}

测试:

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.context.properties.EnableConfigurationProperties;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)

@SpringBootTest(classes = MyProperty.class)

@EnableConfigurationProperties

public class MyPropertyTest {

@Autowired

private MyProperty property;

@Test

public void test() {

assertEquals("test", property.getValue());

}

}

但测试失败并出现错误:

java.lang.AssertionError:

Expected :test

Actual :null

另外,通过在ApplicationRunner中打印应用程序来运行应用程序时,我看到属性值为null.

当我将application.yml用于所有属性时,它具有相同的配置.

如何为属性和测试正确配置以使其工作?

链接到Github repo

解决方法:

很好,我找到了在我的应用程序中使用自定义yaml属性的正确方法.

问题是Spring不支持yaml文件为@PropertySource(link to issue).以下是如何处理spring documentation中描述的解决方法.

因此,为了能够从您需要的yaml文件加载属性:

*实现EnvironmentPostProcessor

*在spring.factories中注册

请访问此github repo以获取完整示例.

另外,非常感谢你的支持,伙计们!

标签:spring-boot-test,java,spring,spring-boot

来源: https://codeday.me/bug/20190910/1798753.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值