Bul*_*oth 4 java spring spring-boot spring-boot-test
我正在使用带有默认application.yml属性文件的Spring Boot 2.0 。我想将它拆分为单独的属性文件,因为它变得很大。
此外,我想编写测试来检查属性的正确性:将出现在生产应用程序上下文(而不是测试上下文)中的值。
这是我的属性文件:src/main/resources/config/custom.yml
my-property:
value: 'test'
Run Code Online (Sandbox Code Playgroud)
属性类:
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;
}
Run Code Online (Sandbox Code Playgroud)
测试:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
但测试失败并出现错误:
java.lang.AssertionError:
Expected :test
Actual :null
Run Code Online (Sandbox Code Playgroud)
我还看到属性值是null通过在ApplicationRunner.
当我用于application.yml所有属性时,它具有相同的配置。
如何为属性和测试设置正确的配置以使其工作?
链接到Github 存储库
很好,我找到了在我的应用程序中自定义 yaml 属性的正确方法。
问题是 Spring 不支持 yaml 文件@PropertySource(链接到 issue)。这是如何处理spring 文档中描述的解决方法。
因此,为了能够从 yaml 文件加载属性,您需要:
* 实现EnvironmentPostProcessor
* 将其注册到spring.factories
请访问此github repo以获取完整示例。
另外,非常感谢小伙伴们的支持!
| 归档时间: |
|
| 查看次数: |
4857 次 |
| 最近记录: |