javascript
springboot 注解动态赋值_SpringBoot 使用 @Value 注解读取配置文件给静态变量赋值
1、application.properties 配置文件CxU免費資源網
mail.username=xue@163.com
mail.password=xue
mail.host=smtp.163.com
mail.smtp.auth=true
2、給普通變量賦值,直接在變量上添加 @Value 注解CxU免費資源網
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 注解無效CxU免費資源網
CxU免費資源網
4、給靜態變量賦值CxU免費資源網
1、使用 set 方法CxU免費資源網
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(推薦使用)CxU免費資源網
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;
}
}
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的springboot 注解动态赋值_SpringBoot 使用 @Value 注解读取配置文件给静态变量赋值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中国空调业务增 18%,大金第二季度净利
- 下一篇: pythonset是什么类型的游戏_Py