这是我参与更文挑战的第 5 天,活动详情查看:更文挑战
前言
SpringBoot框架的普及,给我们开发带来了很多便利。有些系统中用到的全局配置问题,大家也习惯性的放到配置文件中,一方面后期打包部署到线上时,如果仅仅是配置的问题,我们就不用额外打包,仅仅修改配置文件即可;另一方面,对通用的属性做全局配置,就不用每次在项目中去声明。本文主要讲解下如何使用对象去获取配置文件中属性的问题
开发流程
1.properties配置文件声明属性如下:
2.实体类对象声明:通过@Component和@ConfigurationProperties注解将对象注入到spring容器中,后期使用对象时,通过@Autowired注解注入到容器中,然后通过get方法即可获取对应属性信息
@Component
@ConfigurationProperties(prefix = “spring.redis”) //配置文件中对应的前缀
public class RedisConfig {
private String host;
private String password;
private String timeout;
private String port;
public String getRedisHost() {
return redisHost;
}
public void setRedisHost(String redisHost) {
this.redisHost = redisHost;
}
public String getRedisPasswd() {
return redisPasswd;
}
public void setRedisPasswd(String redisPasswd) {
this.redisPasswd = redisPasswd;
}
public int getRedisTimeOut() {
return redisTimeOut;
}
public void setRedisTimeOut(int redisTimeOut) {
this.redisTimeOut = redisTimeOut;
}
public int getRedisPort() {
return redisPort;
}
public void setRedisPort(int redisPort) {
this.redisPort = redisPort;
}
}
复制代码
3.项目中引用:
如上图,引入RedisConfig对象后,就可以利用get方法获取属性信息进行赋值。当然,有时候可能配置信息比较少时,比如简单的配置下文件上传或下载的路径,如果使用此方法未免显得有些麻烦,此时直接可以通过spring的@Value标签引用即可。具体使用如下:
1.application.yml中写法
upload.file.save.path=/home/server/file/upload/
2.controller中写法
public class UserController{
@Value("${upload.file.save.path}")
private String uploadFileSavePath;
}
复制代码
如果大家有更好的方式或方法,欢迎在留言区评论,在编码的道路上一起前行
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END