【发布时间】:2017-11-06 04:49:08
【问题描述】:
我是 Java 世界和 Spring boot 的新手,我正在尝试通过 ConfigurationProperties 注释访问位于 YAML 文件中的一些配置值。
但每当我尝试访问服务中任何位置的配置值时,我都会得到一个空值。
这是application.yml 文件:
my_config:
test: "plop"
这是ValidationProperties 配置类:
@Configuration
@ConfigurationProperties(prefix = "my_config")
public class ValidationProperties {
@NotNull
private String test;
public void setTest(String test) {
this.test = test;
}
public String getTest() {
return this.test;
}
}
使用它的验证器服务:
@Service
public class MyValidator implements ConstraintValidator<MyConstraint, MyEntity> {
@Autowired
private ValidationProperties validationProperties;
@Value("${my_config.test}")
private String test;
@Override
public boolean isValid(MyEntity entity, ConstraintValidatorContext context) {
System.out.println(this.test); // null value, why?
}
}
我还在主类中添加了@EnableConfigurationProperties 注释。
我不确定哪个注释应该做什么,但我显然在这里遗漏了一些东西。另外,如果我尝试从配置文件的 getter 访问值,我会得到一个异常:
System.out.println(this.validationProperties.getTest());
会得到我HV000028: Unexpected exception during isValid call.
【问题讨论】:
-
这篇文章可能对stackoverflow.com/questions/33369878/…有帮助