SpringBoot中怎么自定义配置属性


在SpringBoot中,可以通过创建一个@ConfigurationProperties注解的类来自定义配置属性。以下是一个示例:

    创建一个配置属性类,用@ConfigurationProperties注解标记,同时指定一个前缀来区分不同配置属性:
import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;@Component@ConfigurationProperties(prefix = "custom")public class CustomProperties {private String property1;private int property2;// 省略getter和setter方法}
    application.propertiesapplication.yml中定义自定义配置属性:
custom.property1=value1custom.property2=123
    在需要使用配置属性的地方注入CustomProperties类,SpringBoot会自动读取application.properties中定义的配置属性并注入到CustomProperties实例中:
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class CustomController {@Autowiredprivate CustomProperties customProperties;@GetMapping("/properties")public String getProperties() {return "Property1: " + customProperties.getProperty1() + ", Property2: " + customProperties.getProperty2();}}

这样,就可以在SpringBoot中自定义配置属性并使用了。


上一篇:navicat误删数据恢复失败怎么解决

下一篇:SpringBoot怎么实现服务注册


SpringBoot
Copyright © 2002-2019 测速网 www.inhv.cn 皖ICP备2023010105号
测速城市 测速地区 测速街道 网速测试城市 网速测试地区 网速测试街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!

热门搜索 城市网站建设 地区网站制作 街道网页设计 大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器