Spring注解驱动开发-常用注解@ConfigurationProperties
一、 利用@ConfigurationProperties 读取配置 文件
1、Yml自定义配置信息
esc: ip: 192.168.23.1 port: 9898
2、信息读取配置类
package com.mangoubiubiu.conf; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Data//lombok注解 自动生成get set 方法 @ConfigurationProperties(prefix = "esc") @Component public class EscProperties { private String ip; private String port; }
@Data //lombok的一个注解 自动生成get set方法
@ConfigurationProperties prefix 配置信息的前缀
@Component 只要开启了包扫描 Component-scan 或者在启动类下 被此注解标注的类都会被注入到ioc容器里面
3、Controller 测试类
package com.mangoubiubiu.controller; import com.mangoubiubiu.conf.EscProperties; import io.swagger.annotations.Api; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @Api(tags = "测试模块") @RestController @RequiredArgsConstructor public class TestController { final EscProperties escProperties; @Value("${esc.ip}") private String ip; @Value("${esc.port}") private String port; @GetMapping("/get/userProperties") public ResponseEntity<String> getEscProperties(){ return ResponseEntity.ok("ip:" + escProperties.getIp()); } @GetMapping("/get/getByValue") public ResponseEntity<String> getByValue(){ return ResponseEntity.ok("ip:" + ip); } }
@RequiredArgsConstructor lombok的注解 标注了 此注解 获取相关bean对象时 不需要 再用@Autowird 进行依赖注入
只需要 写
final EscProperties escProperties;
@Value //也可以将配置信息 读取出来, 单个读取
4、测试
@Value
@ConfigurationProperties
发现 都可以将配置 信息 读取 出来 。
本文作者:KwFruit
本文链接:https://www.cnblogs.com/mangoubiubiu/p/15942749.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2021-02-27 @JsonInclude(JsonInclude.Include.NON_EMPTY) 注解无效
2021-02-27 [Vue warn]: Unknown custom element: <el-cascader> - di