SpringBoot 注入静态变量的三种方式、从yml中读取参数
Spring Boot读取properties配置文件中的数据
Spring Boot最常用的3种读取properties****配置文件中数据的方法:
1、使用@Value注解读取
读取properties配置文件时,默认读取的是application.properties。
application.properties:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GatewayController {
@Value("${demo.name}")
private String name;
@Value("${demo.age}")
private String age;
@RequestMapping(value = "/gateway")
public String gateway() {
return "get properties value by ''@Value'' :" +
//1、使用@Value注解读取
" name=" + name +
" , age=" + age;
}
}
这里,如果要把
@Value("${demo.name}")
private String name;
@Value("${demo.age}")
private String age;
部分放到一个单独的类A中进行读取,然后在类B中调用,则要把类A增加@Component注解,并在类B中使用@Autowired自动装配类A,代码如下。
类A:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class ConfigBeanValue {
@Value("${demo.name}")
public String name;
@Value("${demo.age}")
public String age;
}
类B:
import cn.wbnull.springbootdemo.config.ConfigBeanValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GatewayController {
@Autowired
private ConfigBeanValue configBeanValue;
@RequestMapping(value = "/gateway")
public String gateway() {
return "get properties value by ''@Value'' :" +
//1、使用@Value注解读取
" name=" + configBeanValue.name +
" , age=" + configBeanValue.age;
}
}
运行结果如下:
注意:如果@Value${}所包含的键名在application.properties配置文件中不存在的话,会抛出异常:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configBeanValue': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'demo.name' in value "${demo.name}"
2、使用Environment读取
application.properties:
demo.sex=男
demo.address=山东
Java代码:
import cn.wbnull.springbootdemo.config.ConfigBeanValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GatewayController {
@Autowired
private ConfigBeanValue configBeanValue;
@Autowired
private Environment environment;
@RequestMapping(value = "/gateway")
public String gateway() {
return "get properties value by ''@Value'' :" +
//1、使用@Value注解读取
" name=" + configBeanValue.name +
" , age=" + configBeanValue.age +
"<p>get properties value by ''Environment'' :" +
//2、使用Environment读取
" , sex=" + environment.getProperty("demo.sex") +
" , address=" + environment.getProperty("demo.address");
}
}
运行,发现中文乱码:
这里,我们在application.properties做如下配置:
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8
然后修改IntelliJ IDEA,File --> Settings --> Editor --> File Encodings ,将最下方Default encoding for properties files设置为UTF-8,并勾选Transparent native-to-ascii conversion。
重新运行结果如下:
3、使用@ConfigurationProperties注解读取
在实际项目中,当项目需要注入的变量值很多时,上述所述的两种方法工作量会变得比较大,这时候我们通常使用基于类型安全的配置方式,将properties属性和一个Bean关联在一起,即使用注解@ConfigurationProperties读取配置文件数据。
在src\main\resources下新建config.properties配置文件:
demo.phone=10086
demo.wife=self
创建ConfigBeanProp并注入config.properties中的值:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "demo")
@PropertySource(value = "config.properties")
public class ConfigBeanProp {
private String phone;
private String wife;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getWife() {
return wife;
}
public void setWife(String wife) {
this.wife = wife;
}
}
@Component 表示将该类标识为Bean
@ConfigurationProperties(prefix = "demo")用于绑定属性,其中prefix表示所绑定的属性的前缀。
@PropertySource(value = "config.properties")表示配置文件路径。
使用时,先使用@Autowired自动装载ConfigBeanProp,然后再进行取值,示例如下:
import cn.wbnull.springbootdemo.config.ConfigBeanProp;
import cn.wbnull.springbootdemo.config.ConfigBeanValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GatewayController {
@Autowired
private ConfigBeanValue configBeanValue;
@Autowired
private Environment environment;
@Autowired
private ConfigBeanProp configBeanProp;
@RequestMapping(value = "/gateway")
public String gateway() {
return "get properties value by ''@Value'' :" +
//1、使用@Value注解读取
" name=" + configBeanValue.name +
" , age=" + configBeanValue.age +
"<p>get properties value by ''Environment'' :" +
//2、使用Environment读取
" sex=" + environment.getProperty("demo.sex") +
" , address=" + environment.getProperty("demo.address") +
"<p>get properties value by ''@ConfigurationProperties'' :" +
//3、使用@ConfigurationProperties注解读取
" phone=" + configBeanProp.getPhone() +
" , wife=" + configBeanProp.getWife();
}
}
运行结果如下:
GitHub:https://github.com/dkbnull/SpringBootDemo
微信:https://mp.weixin.qq.com/s/swtkNq6CLMsP4uc4PgaVHg
微博:https://weibo.com/ttarticle/p/show?id=2309404275977214638710
————————————————
版权声明:本文为CSDN博主「dkbnull」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/dkbnull/article/details/81953190
SpringBoot中静态变量注入方案
普通变量
首先我们来看看。如何给普通变量注入值?
例如,application-dev.yml 配置文件有如下配置:
给普通变量赋值时,直接在变量声明之上添加@Value()注解即可,如下所示:
这个大家应该很熟悉了,这里就不再赘述。
静态变量
我们来看看昨天的问题,我们想给项目中的文件上传封装一个工具类。阿里云oss的相关信息我们配置在配置文件中,需要将信息注入到工具类中的变量。为了方便直接使用变量,我们把把变量定义为静态变量。当要给静态变量注入值的时候,若是在静态变量声明之上直接添加@Value()注解是无效的。如下图所示。
解决方案
方案一
若要给静态变量赋值,可以使用set()方法注入。
- 类上加入@Component注解
- @Value注解标记set方法
- 方法名(例如setOssUrl)和参数名(例如ossUrl)可以任意命名
如下所示:
方案二
如果你觉得@value注解麻烦。可以使用@ConfigurationProperties注解代替,这样比较简洁
- 前缀要写合适
- 方法名(例如setOssUrl)必须和属性保持一致,例如写为setUrl()会注入失败
- 类上加入@Component注解
方案三
- 类上加入@Component注解
- @PostConstruct注解修饰的方法中进行赋值操作
使用场景
那么问题来啦!我们什么场景下需要把值注入到静态变量?
场景一
场景二
工具类中将值注入静态变量,就可以直接在静态方法之中使用,我本文中遇到的正是这个场景
总结
本文中,我们从一个实际问题出发,探寻了三种在springboot中静态变量注入方案,希望对大家有所帮助。
标题:SpringBoot 注入静态变量的三种方式、从yml中读取参数
作者:llilei
地址:http://solo.llilei.work/articles/2022/07/30/1659146542196.html