@ConfigurationProperties注解

当properties文件遇到以下几种情况该怎么办?

  1. 希望给属性加上强类型校验避免配错,例如超时时间必须是整数
  2. 希望在不显式配置某个属性的时候,该属性也有默认值
  3. 注意到IDEA中对spring的公共属性有代码提示,怎么让自定义属性也有代码提示

在Java类中使用@Value(${property:default})倒是可以设置默认值,但不能解决1、3,并且每个字段都要加@Value注解,很繁琐。这时候就靠@ConfigurationProperties出马了。

用法

  1. @ConfigurationProperties注解可以用在Class上,或Configuration类的方法上(也就是@Bean)
  2. 使用该注解后,该bean的字段都会映射为properties文件的属性
  3. 支持嵌套
  4. 属性(字段)在Java里小驼峰命名,在properties文件中是短横线“-”分隔,框架会自动转换
  5. bean必须有getter/setter
  6. 如果应用类型是springboot应用,在IDEA中还会有自动提示
  7. 属性的javadoc注释会在IDEA的自动提示中显示出来

步骤

1. 定义配置类

例如:

@ConfigurationProperties(prefix = "server")
@Component
public class ServerProperties {

    /**
     * 会映射到属性 server.name
     */
    private String name;

    private Host host;

    // ... getter and setters
    @Component
    private static class Host {

        // 映射到 server.host.ip
        private String ip;

        // 映射到 server.host.port
        private int port;

        // ... getter and setters

    }

}

2. IDEA可能会报错

报错:spring boot Configuration Annotation Proessor not found in classpath

解决,在pom文件中加上:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
    <scope>provided</scope>
</dependency>

3. rebuild project

这时候可能还是没有自动提示,因为自动提示的信息是保存在 target/classes/META-INF/spring-configuration-metadata.json 文件中,而步骤2加入的processor会在编译时把@ConfigurationProperties标记的bean写入该文件,因此只需要重新编译,检查该文件存在,就可以有自动提示。

WARNING

如果到这里还是没有自动提示,可能是由于IDEA未把properties文件识别为spring boot配置文件,可以进入Project Settings - Modules,把properties设置为spring boot。

4. 使用配置

例:

@Controller
public class XXXController {

    @Autowired
    private xxxProperties prop;
}

WARNING

如果xxxProperties类没有被声明为@Component,可以在应用主类加上@EnableConfigurationProperties,框架会自动扫描@ConfigurationProperties注解。

就酱 😄

Last Updated 2024/11/24 20:50:53