Spring的@DefaultValue注解

https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/properties/bind/DefaultValue.html

该注解可以用于指定在绑定不可变属性时的默认值。该注解也可以与嵌套属性一起使用,以指示应始终绑定一个值(而不是绑定null)。只有当绑定器使用的属性源中找不到该属性时,才会使用这个注解中的值。例如,当在绑定到@ConfigurationProperties时,如果属性存在于Environment中,即使该属性的值为空,也不会使用该属性的默认值。

@DefaultValue注解允许你为Spring Boot应用程序中的配置属性指定一个默认值。这个默认值只在两种情况下会被使用:

  1. 当绑定器(Binder)在属性源(例如application.propertiesapplication.yml文件)中找不到该属性时。
  2. 当该属性是不可变的(即,没有对应的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;
        }

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值