介绍
本篇文章给大家分享的是有关SpringBoot项目中利用@ value注解如何实现给静态变量赋值,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
1,应用程序。属性配置文件
mail.username=xue@163.com mail.password=雪 mail.host=smtp.163.com mail.smtp。auth=true
2,给普通变量赋值,直接在变量上添加@ value注解
进口org.springframework.beans.factory.annotation.Value; 公开课MailConfig { @ value (“$ {mail.username}“) 私人字符串的用户名; @ value (“$ {mail.password}“) 私人密码字符串; @ value (“$ {mail.host}“) 私人字符串主机; }
3,给静态变量赋值,直接在静态变量上添加@ value注解无效
4,给静态变量赋值
1,使用集方法
进口org.springframework.beans.factory.annotation.Value; 进口org.springframework.stereotype.Component; @ component 公开课MailConfig { 公共静态字符串的用户名; 公共静态字符串密码; 公共静态字符串主机; @ value (“$ {mail.username}“) 公共空间setUsername(字符串的用户名){ 这一点。用户名=用户名; } @ value (“$ {mail.password}“) 公共空间向setPassword(字符串密码){ 这一点。密码=密码; } @ value (“$ {mail.host}“) 公共空间setHost (String主机){ 这一点。主机=主机; } }
2,使用@PostConstruct(推荐使用)
进口org.springframework.beans.factory.annotation.Value; 进口org.springframework.stereotype.Component; 进口javax.annotation.PostConstruct; @ component 公开课MailConfig { 公共静态字符串的用户名; 公共静态字符串密码; 公共静态字符串主机; @ value (“$ {mail.username}“) 私人字符串的用户名; @ value (“$ {mail.password}“) 私人密码字符串; @ value (“$ {mail.host}“) 私人字符串主机; @PostConstruct 公共空间init () { 用户名=用户名; 密码=密码; 主机=主机; } }
以上就是SpringBoot项目中利用@ value注解如何实现给静态变量赋值,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注行业资讯频道。