1、application.properties 配置文件

mail.username=xue@163.com
mail.password=xue
mail.host=smtp.163.com
mail.smtp.auth=true

2、给普通变量赋值,直接在变量上添加 @Value 注解

import org.springframework.beans.factory.annotation.Value;

public class MailConfig {
  @Value("${mail.username}")
  private String username;
  @Value("${mail.password}")
  private String password;
  @Value("${mail.host}")
  private String host;
}

3、给静态变量赋值,直接在静态变量上添加 @Value 注解无效

SpringBoot 使用 @Value 注解读取配置文件给静态变量赋值

4、给静态变量赋值

1、使用 set 方法

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MailConfig {
  public static String username;
  public static String password;
  public static String host;

  @Value("${mail.username}")
  public void setUsername(String username) {
    this.username = username;
  }

  @Value("${mail.password}")
  public void setPassword(String password) {
    this.password = password;
  }

  @Value("${mail.host}")
  public void setHost(String host) {
    this.host = host;
  }
}

2、使用 @PostConstruct(推荐使用)

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class MailConfig {
  public static String USERNAME;
  public static String PASSWORD;
  public static String HOST;

  @Value("${mail.username}")
  private String username;
  @Value("${mail.password}")
  private String password;
  @Value("${mail.host}")
  private String host;

  @PostConstruct
  public void init() {
    USERNAME = username;
    PASSWORD = password;
    HOST = host;
  }
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。