代码之家  ›  专栏  ›  技术社区  ›  夢のの夢

从2.2到2.3,SpringBoot为@ConfigurationProperties添加了@Component或@EnableConfigurationProperties的要求

  •  0
  • 夢のの夢  · 技术社区  · 5 年前

    我最近将一个SpringBoot项目从2.2.0升级到了2.3.1,但是我注意到在Spring2.2.0之前出现了一个错误。

    未通过@EnableConfigurationProperties注册、标记为Spring组件或通过@ConfigurationPropertiesScan扫描

    @Data
    @ConfigurationProperties("sftp")
    public class SftpProperties {
        String host;
        String user;
        String password;
        String baseDir;
    }
    

    在早前的Spring引导版本中——我相信是2.0.2或其他版本——我用 @Component 所以它在类路径扫描时被提取。但从2.2开始,我读到它不再是必要的,因此我删除了 @组成部分 . 这似乎是一个细微的改进,但从2.3.x开始,就不再支持它了。为什么会这样或者我遗漏了什么?

    0 回复  |  直到 5 年前
        1
  •  0
  •   M. Deinum    5 年前

    @ConfigurationProperties 不会使类成为弹簧组件。您还需要添加 @ConfigurationPropertiesScan 在应用程序中,启用对带注释的类的扫描 @配置属性 .

    看到了吗 release notes

        2
  •  0
  •   Ankush Sharma    5 年前

    在Spring2.2之前,主类应该有@EnableConfigurationProperties(SftpProperties.class),或者在SftpProperties类的上面使用@Configuration。

    但是在2.2spring通过classpath扫描找到并注册@ConfigurationProperties类之后,就不需要这些注释了,您只需要使用@ConfigurationPropertiesScan(“property package path”)注释来扫描配置属性类的自定义位置。

    @SpringBootApplication
    @ConfigurationPropertiesScan("com.app.properties")
    public class DemoApplication { 
     
        public static void main(String[] args) {   
            SpringApplication.run(DemoApplication.class, args); 
        } 
    }