java - 如何从 yaml 文件中设置模型类变量的默认值?
问题描述
在服务文件中,我会简单地使用@Value
并初始化变量。我已经在模型类中尝试过这种方法,但是(我假设事情是如何自动连接的,并且它是一个模型类)这导致它始终是null
.
对此的需求在于,在不同的环境中,默认值总是不同的。
@Value("${type}")
private String type;
解决方案
我会避免尝试在模型中使用 Spring 逻辑,因为它们本身不是 Spring bean。也许使用某种形式的创建模型(模式)bean,在其中构建模型,例如:
@Component
public class ModelFactory {
@Value("${some.value}")
private String someValue;
public SomeModel createNewInstance(Class<SomeModel> clazz) {
return new SomeModel(someValue);
}
}
public class SomeModel {
private String someValue;
public SomeModel(String someValue) {
this.someValue = someValue;
}
public String getSomeValue() {
return someValue;
}
}
@ExtendWith({SpringExtension.class})
@TestPropertySource(properties = "some.value=" + ModelFactoryTest.TEST_VALUE)
@Import(ModelFactory.class)
class ModelFactoryTest {
protected static final String TEST_VALUE = "testValue";
@Autowired
private ModelFactory modelFactory;
@Test
public void test() {
SomeModel someModel = modelFactory.createNewInstance(SomeModel.class);
Assertions.assertEquals(TEST_VALUE, someModel.getSomeValue());
}
}