springboot注解读取yml文件

本文介绍了一个使用SpringBoot框架结合JPA实现的项目案例,重点讲解了如何通过application.yml文件进行灵活配置,包括基本属性设置及通过@Value注解读取配置的方法。

代码位置:https://github.com/Kevin-Karl-Wang/springboot-jpa
application.yml文件内容:

test read ymlfile

fruit:
name: apple
amount: 5

自定义的属性和值

myProps:
simpleProp: simplePropValue
arrayProps: 1,2,3,4,5
listProp1:
- name: abc
value: abcValue
- name: efg
value: efgValue
listProp2:
- config2Value1
- config2Vavlue2
mapProps:
key1: value1
key2: value2

server:
port: 8080
address: localhost
context-path: /springboot-jpa

1.@value注解 这里写图片描述
访问路径:http://localhost:8080/springboot-jpa/testyml这里写图片描述

2.javaBean:这里写图片描述这里写图片描述
这里写图片描述

### Spring Boot 使用注解读取 YML 文件 在 Spring Boot 应用程序中,可以利用 `@Value` 和自定义配置类配合 `@ConfigurationProperties` 注解读取 YAML 配置文件的内容。 #### 利用 @Value 注解读取单个属性 对于简单的场景可以直接采用 `@Value` 来获取特定键对应的值: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class SimpleConfigReader { @Value("${app.name}") private String appName; public void printAppName() { System.out.println("Application Name is : " + appName); } } ``` 此方法适用于少量配置项的情况[^1]。 #### 使用 @ConfigurationProperties 绑定复杂对象 当有多个相关联的设置时推荐创建专门的数据结构并标注为 `@ConfigurationProperties` 类型以便批量注入: 首先,在实体类上加上必要的元数据声明: ```java import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "wx.template") public class WxTemplateProperties { private String appId; private String appSecret; // getters and setters... } ``` 接着可以在服务层自动装配该实例从而访问其内部字段: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class WeChatService { private final WxTemplateProperties wxTemplateProperties; @Autowired public WeChatService(WxTemplateProperties wxTemplateProperties) { this.wxTemplateProperties = wxTemplateProperties; } public void showWechatInfo(){ System.out.printf("App ID:%s, App Secret:%s%n", wxTemplateProperties.getAppId(), wxTemplateProperties.getAppSecret()); } } ``` 这种方式不仅简化了代码逻辑而且提高了可维护性和扩展性[^3]。 为了确保安全性和灵活性,还可以考虑集成第三方库如 Jasypt 对敏感信息进行加密处理后再存入配置文件内[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值