配置属性中的默认值

问题描述 投票:0回答:1

使用Spring Boot @ConfigurationProperties无论如何都要指定默认值?如在编程而不是从application.propertiesapplication.yaml加载

我尝试了以下似乎没有用的以下内容。

@ConfigurationProperties(prefix = "test.metrics", ignoreUnknownFields = false)
@NoArgsConstructor
@Data
public class MetricsProperties {
    public static final String DEFAULT_MANAGEMENT_CONTEXT_PATH = "/test";
    public static final Integer DEFAULT_MANAGEMENT_PORT = xxxx;

    private final Management management = new Management();

    @NoArgsConstructor
    @Data
    public static class Jmx {
        private boolean enabled = true;
    }

    @NoArgsConstructor
    @Data
    public static class Management {
        private String contextPath = DEFAULT_MANAGEMENT_CONTEXT_PATH;
        private Integer port = DEFAULT_MANAGEMENT_PORT;
    }
}

在这种情况下,我无法看到contextPathport

似乎无法在Spring文档中找到任何内容。

spring spring-boot configuration
1个回答
-1
投票

我建议做这样的事情。

在这里你设置默认值5400,以防缺失值

@Configuration
@ConfigurationProperties
public class SessionConfig {

    @Value("${server.session.timeout:5400}")
    public int defaultMaxInactiveInterval;

}

然后你可以自动配置配置

@Configuration
@EnableSpringHttpSession
@ConditionalOnProperty(name = "use.redis.session.store", havingValue = "false", matchIfMissing = true)
public class InMemorySessionConfig {

    @Autowired
    private SessionConfig sessionConfig;

    @Bean
    public MapSessionRepository sessionRegistry() {
        MapSessionRepository sessionRepository = new MapSessionRepository();
        sessionRepository.setDefaultMaxInactiveInterval(sessionConfig.defaultMaxInactiveInterval);
        return sessionRepository;
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.