该注解可以用于指定在绑定不可变属性时的默认值。该注解也可以与嵌套属性一起使用,以指示应始终绑定一个值(而不是绑定null)。只有当绑定器使用的属性源中找不到该属性时,才会使用这个注解中的值。例如,当在绑定到@ConfigurationProperties时,如果属性存在于Environment中,即使该属性的值为空,也不会使用该属性的默认值。
@DefaultValue
注解允许你为Spring Boot应用程序中的配置属性指定一个默认值。这个默认值只在两种情况下会被使用:
- 当绑定器(
Binder
)在属性源(例如application.properties
或application.yml
文件)中找不到该属性时。 - 当该属性是不可变的(即,没有对应的setter方法)并且没有在属性源中被显式设置时。
@DefaultValue
注解通常与@ConfigurationProperties
注解一起使用,用于处理那些可能没有在配置文件中显式设置的属性。通过指定默认值,你可以确保应用程序在缺少某些配置时仍然能够正常运行,而不会因为找不到必要的配置信息而失败。
需要注意的是,如果属性已经在Environment
中被设置(例如,通过命令行参数、系统属性或其它方式),那么即使该属性的值为空,也不会使用@DefaultValue
注解中指定的默认值。这是因为一旦属性被设置,Spring Boot就会优先考虑使用这个已经设置的值,而不是使用默认值。
此外,@DefaultValue
注解也可以与嵌套属性一起使用。在处理嵌套属性时,如果某个子属性的值没有被设置,你可以使用@DefaultValue
注解来指定一个默认值。这样,即使父属性被设置了,但子属性没有被显式设置,Spring Boot仍然会使用@DefaultValue
注解中指定的默认值来初始化子属性。
下面的示例来自spring官网:
https://docs.spring.io/spring-boot/docs/3.2.0/reference/htmlsingle/#features.external-config.typesafe-configuration-properties.constructor-binding
import java.net.InetAddress;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.DefaultValue;
@ConfigurationProperties("my.service")
public class MyProperties {
private final boolean enabled;
private final InetAddress remoteAddress;
private final Security security;
public MyProperties(boolean enabled, InetAddress remoteAddress, Security security) {
this.enabled = enabled;
this.remoteAddress = remoteAddress;
this.security = security;
}
public boolean isEnabled() {
return this.enabled;
}
public InetAddress getRemoteAddress() {
return this.remoteAddress;
}
public Security getSecurity() {
return this.security;
}
public static class Security {
private final String username;
private final String password;
private final List<String> roles;
public Security(String username, String password, @DefaultValue("USER") List<String> roles) {
this.username = username;
this.password = password;
this.roles = roles;
}
public String getUsername() {
return this.username;
}
public String getPassword() {
return this.password;
}
public List<String> getRoles() {
return this.roles;
}
}
}