【问题标题】:Spring Boot Use Custom Properties ServiceSpring Boot 使用自定义属性服务
【发布时间】:2017-06-26 08:40:18
【问题描述】:

我正在处理一个遗留项目,它有自己的 PropertyService 类来管理可重新加载的属性等。

这东西工作得很好,但问题是我现在有这个属性服务,用于我的项目,还有一个用于 Spring Boot 相关属性的 application.yml。

问题是:有没有办法告诉 Spring Boot 从属性提供程序(自定义类或适配器之类)加载属性?

这样我只能通过现有模块管理我的属性

感谢您的帮助!

【问题讨论】:

    标签: spring spring-boot properties


    【解决方案1】:

    尝试@ConfigurationProperties 自定义属性加载(见the example

    代码示例

    @Configuration
    @ConfigurationProperties(locations = "classpath:mail.properties", prefix = "mail")
    public class MailConfiguration {
    
        public static class Smtp {
    
            private boolean auth;
            private boolean starttlsEnable;
    
            // ... getters and setters
        }
    
        @NotBlank
        private String host;
        private int port;  
        private String from;
        private String username;
        private String password;
        @NotNull
        private Smtp smtp;
    
        // ... getters and setters   
    
        @Bean
        public JavaMailSender javaMailSender() {
            // omitted for readability
        }
    }
    

    所以你定义了一个实际上返回属性的bean

    【讨论】:

    • 我尝试过使用“server.port”,所以在我的课堂上我有@ConfigurationProperties(prefix = "server") 和一个名为“int port”的属性。然而,getter 永远不会被调用。你确定你可以像这样覆盖 Spring Boot 属性吗?
    猜你喜欢
    • 2020-10-26
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 2020-04-30
    • 2018-11-14
    • 2016-10-23
    相关资源
    最近更新 更多