从properties文件中加载配置项
配置项比如:

  1. logic.mail.enable=true

对字段使用@Value注解

  1. @Value("${logic.mail.enable}")
  2. private Boolean enable;

对类使用@ConfigurationProperties注解

tips:

  • 对应的字段需要有公用的set方法

    1. @Setter
    2. @ConfigurationProperties(prefix = "logic.mail")
    3. public class SystemMailServiceImpl{
    4. private Boolean enable;
    5. }

    使用这种方式建议配置Spring Boot Configuration Processor完成自动补全

    1. <dependency>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-configuration-processor</artifactId>
    4. <optional>true</optional>
    5. </dependency>

    引入该依赖后的效果:
    tips:

  • 对应字段有set方法才能被应用,同时再有get方法,才可以被提示到

  • 如果没有生效,请使用rebuild方法

image.png

使类实现EnvironmentAware接口

  1. public class SystemMailServiceImpl implements EnvironmentAware{
  2. private Boolean enable;
  3. @Override
  4. public void setEnvironment(Environment environment) {
  5. this.enable = environment.getProperty("logic.mail.enable")
  6. }
  7. }