【问题标题】:@ConfigurationProperties on fields字段上的@ConfigurationProperties
【发布时间】:2016-03-16 10:40:00
【问题描述】:

@ConfigurationProperties定义属性时,我可以定义特定字段的前缀而不是整个类吗?

例如,假设我们有一个 Properties 类

@ConfigurationProperties(prefix = "com.example")
public class MyProperties {
    private String host;
    private String port;
    // Geters and setters...
}

这会将字段hostport 绑定到com.example.hostcom.example.port。假设我想将port 绑定到com.example.something.port。这样做的方法是定义一个内部类Something 并在那里添加属性port。但是如果我需要更多前缀,它会变得太麻烦。我尝试在setter上添加@ConfigurationProperties,因为注解的目标是ElementType.TYPEElementType.METHOD

@ConfigurationProperties(prefix = "com.example.something.port")
public void setPort(int port) {...}

但它最终没有奏效。除了通过内部类之外,还有其他方法可以自定义前缀吗?

【问题讨论】:

    标签: java properties spring-boot


    【解决方案1】:
    1. 如果要映射单个属性,只需使用@Value注解即可。

    2. 如果您有群组,例如像这样:

      test1.property1=... test1.test2.property2=... test1.test2.property3=...

    你可以使用

    import javax.validation.constraints.NotNull;
    
    import lombok.Getter;
    import lombok.Setter;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Configuration;
    
    @Getter
    @Setter
    @Configuration
    @EnableConfigurationProperties
    @ConfigurationProperties(locations = "classpath:myapp.properties")
    public class ApplicationProperties {
    
        private String property1;
        private Test2 test2;
    
        @Getter
        @Setter
        @ConfigurationProperties(prefix = "test2")
        public static class Test2 {
            @NotNull
            private String property2;
            @NotNull
            private String property3;
        }
    }
    

    【讨论】:

    • 你在哪里使用@Value注解?
    • @Value 注释是为了防止你有简单的值。这在示例中没有解释,因为它是众所周知的构造。如果您仍然需要示例,请告诉我,我将在此处添加它
    • 抱歉,我读多了你解释了两种不同的方法,我认为这是一个单一的解决方案。
    猜你喜欢
    • 2021-01-02
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 2014-11-26
    • 2018-07-08
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多