首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >字段上的@ConfigurationProperties

字段上的@ConfigurationProperties
EN

Stack Overflow用户
提问于 2015-12-10 17:17:10
回答 1查看 8.2K关注 0票数 5

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

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

代码语言:javascript
复制
@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

代码语言:javascript
复制
@ConfigurationProperties(prefix = "com.example.something.port")
public void setPort(int port) {...}

但到头来还是行不通的。除了内部类之外,还有其他方法来自定义前缀吗?

EN

回答 1

Stack Overflow用户

发布于 2015-12-10 20:04:54

  1. 如果要映射单个属性,只需使用@Value注释即可。
  2. 如果你有这样的小组,例如: test1.property1=...test1.test2.property2=...test1.test2.property3=...

您可以使用

代码语言:javascript
复制
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;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34207920

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档