Spring Boot 3 record 作为配置类设置默认值

Spring Boot About 1,042 words

需求

使用Java16中提供的record新特性作为配置类,设置默认值。

YAML

blog:
  portal:
    title: Blog
    author: fendoudebb
    github: https://github.com/fendoudebb/z-blog-spring-native

代码

使用@DefaultValue

@ConfigurationProperties(prefix = "blog.portal")
public record PortalProperties(
        String title,
        @DefaultValue("fendoudebb") String author,
        @DefaultValue({"Spring Boot3", "Java17", "Spring Native"}) Set<String> keywords,
        @DefaultValue("100") Integer stars,
        @DefaultValue("true") Boolean release,
        String github) {
}

源码

可以看到@DefaultValue@Target适用的元素类型提供了RECORD_COMPONENT

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.PARAMETER, ElementType.RECORD_COMPONENT })
@Documented
public @interface DefaultValue {

    String[] value() default {};

}

ElementTypeJava16后提供了RECORD_COMPONENT类型。

public enum ElementType {

    // ...

    /**
     * Record component
     *
     * @jls 8.10.3 Record Members
     * @jls 9.7.4 Where Annotations May Appear
     *
     * @since 16
     */
    RECORD_COMPONENT;
}
Views: 1,199 · Posted: 2023-02-03

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh