SpringBoot 使用 @Value 注解读取配置文件给静态变量赋值
1、application.properties 配置文件
mail.username=xue@163.commail.password=xuemail.host=smtp.163.commail.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;@Componentpublic 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;@Componentpublic 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 静态变量赋值内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!
相关文章:
1. Matplotlib可视化之添加让统计图变得简单易懂的注释2. Ajax 的初步实现(使用vscode+node.js+express框架)3. pygame实现井字棋之第三步逻辑优化4. Spring MVC+ajax进行信息验证的方法5. vue中watch监听路由传来的参数变化问题6. vscode运行php报错php not found解决办法7. python中dlib库的详细安装方法8. Ajax对xml信息的接收和处理操作实例分析9. python使用pywinauto驱动微信客户端实现公众号爬虫10. 一个用xslt样式将xml解析为xhtml的类TransformBinder(兼容FF和IE7.0)

网公网安备