Java EE 目录:https://blog.csdn.net/dkbnull/article/details/87932809
Spring Boot 专栏:https://blog.csdn.net/dkbnull/category_9278145.html
Spring Cloud 专栏:https://blog.csdn.net/dkbnull/category_9287932.html
Spring Boot最常用的3种读取properties配置文件中数据的方法:
1、使用@Value注解读取
读取properties配置文件时,默认读取的是application.properties。
application.properties:
demo.name=Name
demo.age=18
Java代码:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
@RestControllerpublic
class GatewayController {
//1、使用@Value注解读取
@Value("${demo.name}")
private String name;
@Value("${demo.age}")
private String age;
@RequestMapping(value = "/gateway")
public String gateway() {
return "get properties value by ''@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-8spring.http.encoding.charset=UTF-8spring.http.encoding.enabled=truespring.http.encoding.force=truespring.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
#jwt
jwt:
header: Authorization
# 令牌前缀
token-start-with: Bearer
# 必须使用最少88位的Base64对该令牌进行编码
base64-secret: ZmQ0ZGI5NjQ0MDQwY2I4MjMxY2Y3ZmI3MjdhN2ZmMjNhODViOTg1ZGE0NTBjMGM4NDA5NzYxMjdjOWMwYWRmZTBlZjlhNGY3ZTg4Y2U3YTE1ODVkZDU5Y2Y3OGYwZWE1NzUzNWQ2YjFjZDc0NGMxZWU2MmQ3MjY1NzJmNTE0MzI=
# 令牌过期时间 此处单位/毫秒 ,默认4小时,可在此网站生成 https://www.convertworld.com/zh-hans/time/milliseconds.html
token-validity-in-seconds: 14400000
# 在线用户key
online-key: online-token
# 验证码
code-key: code-key
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "jwt")
public class SecurityProperties {
/** Request Headers : Authorization */
private String header;
/** 令牌前缀,最后留个空格 Bearer */
private String tokenStartWith;
/** 必须使用最少88位的Base64对该令牌进行编码 */
private String base64Secret;
/** 令牌过期时间 此处单位/毫秒 */
private Long tokenValidityInSeconds;
/** 在线用户 key,根据 key 查询 redis 中在线用户的数据 */
private String onlineKey;
/** 验证码 key */
private String codeKey;
public String getTokenStartWith() {
return tokenStartWith + " ";
}
}
创建ConfigBeanProp并注入config.properties中的值:
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");
}
}
@Component 表示将该类标识为Bean
@ConfigurationProperties(prefix = "demo")用于绑定属性,其中prefix表示所绑定的属性的前缀。
@PropertySource(value = "config.properties")表示配置文件路径。
使用时,先使用@Autowired自动装载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;
@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");
}
}
运行结果如下:
GitHub:https://github.com/dkbnull/SpringBootDemo
微信:https://mp.weixin.qq.com/s/swtkNq6CLMsP4uc4PgaVHg
微博:https://weibo.com/ttarticle/p/show?id=2309404275977214638710
---------------------
作者:dkbnull
来源:CSDN
原文:https://blog.csdn.net/dkbnull/article/details/81953190?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
版权声明:本文为作者原创文章,转载请附上博文链接!
内容解析By:CSDN,CNBLOG博客文章一键转载插件