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 注解无效
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;
}
}
到此这篇关于springboot 使用 @value 注解读取配置文件给静态变量赋值的文章就介绍到这了,更多相关springboot @value 静态变量赋值内容请搜索萬仟网以前的文章或继续浏览下面的相关文章希望大家以后多多支持萬仟网!
希望与广大网友互动??
点此进行留言吧!