通常,我使用一个类从yml加载所有配置,并通过自动装配配置使它们在我的应用程序中可用。在我尝试通过添加@Validated批注来验证配置之前,此方法效果很好。
如果验证失败,则应用程序无法启动,并且我收到一条消息,其中包含设置错误的属性。 如果验证成功,即使通过调试也可以看到,我的自动装配配置为空,即使从yml文件读取并设置了正确的值。
//full configuration class
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
@Component
@ConfigurationProperties(prefix = "config")
@Validated
public class ConfigurationStore {
@Valid
public MyConfiguration myConfiguration = new MyConfiguration();
public ConfigurationStore setMyConfiguration(MyConfiguration myConfiguration) {
this.myConfiguration = myConfiguration;
return this;
}
public static class MyConfiguration {
@NotBlank
public String configuredString;
public void setConfiguredString(String configuredString) {
this.configuredString = configuredString;
}
}
}
//class where autowired configuration is always null
import {package}.ConfigurationStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import(ConfigurationStore.class)
public class MyConfig {
private ConfigurationStore configurationStore;
@Autowired
public MyConfig(ConfigurationStore configurationStore) {
this.configurationStore = configurationStore;
}
@Bean
public String returnIt() {
return configurationStore.myConfiguration.configuredString;
}
}
删除@Validated会删除验证功能。保留它会导致自动装配配置为空。 我期望的是配置和验证可以同时进行。