@ConfigurationProperties-在缺少/未解析属性的情况下出现意外行为



我正在开发一个基于spring-boot 2.4.3的应用程序。

@ConfigurationProperties(prefix = "keystore")
@ConstructorBinding
@Validated
@AllArgsConstructor
@Getter
public class KeyStoreProperties {
@NotBlank(message = "keystore password should be provided")
private final String password;
@NotBlank(message = "keystore path should be provided")
private final String path;
}
@Service
public class KeyStoreService {
private final KeyStoreProperties properties;
private KeyStore keyStore;
public KeyStoreService(KeyStoreProperties properties) {
this.properties = properties;
}
}
...

application.properties

keystore.password=${KEY_STORE_PASSWORD}
keystore.path=keystore/keystore.p12

我预计,如果KEY_STORE_PASSWORD环境。变量,则KeyStoreProperties.password将解析为null。但它有一个值'${KEY_STORE_PASSWORD}'

根据https://github.com/spring-projects/spring-boot/issues/10463应该是一个特性,但在我看来,它会导致意外的行为。这会给我正在运行的系统带来麻烦,因为密钥库的密码设置为错误的值。我希望在应用程序启动时出现故障,比如";未解析的属性&";。我怎样才能到达那里?在我的观点中,一个更好的解决方案是通过引入一个额外的属性,如@ConfigurationProperties(ignoreUnsolable=false(,使其可配置。

由于Spring认为这是一个功能,您可以向两个属性添加Regex验证:

public class KeyStoreProperties {
@Pattern(regexp="${S*}", message="unresolved property")  
@NotBlank(message = "keystore password should be provided")
private final String password;
@Pattern(regexp="${S*}", message="unresolved property")  
@NotBlank(message = "keystore path should be provided")
private final String path;
}

相关内容

最新更新