
自定义属性SpringBoot默认的配置文件为application.properties或者application.yml,应用启动时会自动加载此文件,无需手动引入。
在application.properties中定义属性值
#自定义属性 rumenz.name=rumenz rumenz.url=https://rumenz.com
通过@Value注解来获取值
@RestController
@RequestMapping("/rumenz")
public class RumenzController {
@Value("${rumenz.name}")
private String rumenzName;
@Value("${rumenz.url}")
private String rumenzUrl;
@RequestMapping("/index")
public String index(){
return rumenzName+":::"+rumenzUrl;
}
}
配置绑定访问http://127.0.0.1:8080/rumenz/index路径,会返回rumenz:::https://rumenz.com。
有时间有需要注入的属性比较多,一个一个绑定很繁琐,官方建议通过Bean的方式加载。
application.properties配置文件定义属性值
com.rumenz.id=1 com.rumenz.name=hello
RumenzConfig配置文件
@Component
@ConfigurationProperties(prefix = "com.rumenz")
public class RumenzConfig {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
测试
浏览器输入http://127.0.0.1:8080/rumenz/index1,返回1:::hello
@RestController
@RequestMapping("/rumenz")
public class RumenzController {
@Autowired
RumenzConfig rumenzConfig;
@RequestMapping("/index1")
public String index1(){
return rumenzConfig.getId()+":::"+rumenzConfig.getName();
}
}
参数引用
在application.properties中的各个参数之间可以直接引用来使用
com.rumenz.id=1
com.rumenz.name=hello
com.rumenz.des=${com.rumenz.name}${com.rumenz.id}
新建RumenzController测试
@RestController
@RequestMapping("/rumenz")
public class RumenzController {
@Value("${com.rumenz.des}")
private String rumenzDes;
@RequestMapping("/index2")
public String index2(){
//配置文件参数引用
//com.rumenz.des=${com.rumenz.name}${com.rumenz.id}
return rumenzDes;
}
}
自定义的配置文件浏览器访问http://127.0.0.1:8080/rumenz/index2返回hello1
一般的配置项都在application.properties中,很多时候有一些配置信息我们想单独存放。比如我们创建了一个rumenz.properties的自定义配置文件。
com.rumenz.tag=入门小站 com.rumenz.txt=这是一个教程网站
自定义的配置文件系统不会自动加载,需要用@PropertySource加载。需要加载多个可以用设置数组。
测试
@RestController
@RequestMapping("/rumenz")
@PropertySource(value="classpath:rumenz.properties",encoding = "utf-8")
public class Rumenz1Controller {
@Value("${com.rumenz.tag}")
private String rumenzTag;
@Value("${com.rumenz.txt}")
private String rumenzTxt;
@RequestMapping("/index3")
public String index3(){
//这是自定义配置中配置的属性
return rumenzTag+rumenzTxt;
}
}
加载多个自定义配置文件
@PropertySource(value = {
"classpath:rumenz.properties",
"classpath:rumenz2.properties",
}, encoding = "utf-8")
本小结源码地址:
GitHub:https://github.com/mifunc/springboot/tree/main/lession6Gitee:https://gitee.com/rumenz/springboot/tree/master/lession6https://rumenz.com/rumenbiji/springboot-basic-config.html
介绍
我的博客 https://rumenz.com/我的工具箱 https://tooltt.com/微信公众号:【入门小站】
关注【入门小站】回复【1001】获取 linux常用命令速查手册关注【入门小站】回复【1003】获取 LeetCode题解【java语言实现】关注【入门小站】回复【1004】获取 Java基础核心总结关注【入门小站】回复【1009】获取 阿里巴巴Java开发手册
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)