SpringBoot bean映射yml中的属性举例
2024-10-20 00:29:23
pom:导入配置文件处理器,配置文件进行绑定就会有提示
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring‐boot‐configuration‐processor</artifactId>
<optional>true</optional>
</dependency>
yml:
user:
name: lisa
postcode: 610424199612112800
user.java方式一:使用@ConfigurationProperties注解实现批量对应属性值
package com.pecool.customer.entity; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; @Component
@ConfigurationProperties(prefix="user")
public class User { private String name;
private String postcode;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
@Override
public String toString() {
return "User [name=" + name + ", postcode=" + postcode + "]";
} }
user.java方式二:在属性上使用spring 的@Value注解也可以获取到yml或properties中的值
package com.pecool.customer.entity; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; @Component
//@ConfigurationProperties(prefix="user")
public class User { @Value("${user.name}")
private String name; @Value("${user.postcode}")
private String postcode;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
@Override
public String toString() {
return "User [name=" + name + ", postcode=" + postcode + "]";
} }
Test.java
package com.pecool; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import com.pecool.customer.entity.User; @SpringBootTest
@RunWith(SpringRunner.class)
public class TestA { @Autowired
private User user; @Test
public void xxx(){
System.out.println(user);
} }
最新文章
- WCF学习之旅—TCP双工模式(二十一)
- LYDSY模拟赛day3 涂色游戏
- bootstrap插件学习-bootstrap.typehead.js
- linux VFS 内核数据结构
- 二、UITableView和它的亲戚们
- U盘安装Win7系统教程
- MySQL里求给定的时间是所在月份的第几个礼拜
- 设计模式(三)-- 适配器模式(Adapter)
- jsp篇 之 Jsp中的内置对象和范围对象
- 左手是“Python”的身体,右手是“R”的灵魂,你爱哪个?
- c++简单学习
- [转]Linux下网络常用命令和工具
- 关于Ctime库
- ISO8583组包、解包
- 使用JAAS登录kerberos服务器
- docker搭建redis未授权访问漏洞环境
- Linux内核(3) - 分析内核源码如何入手(下)
- C++和Java函数传递数组参数比较
- 【Error】:10061由于目标计算机积极拒绝,无法连接
- Centos7安装Apache Http服务器无法访问如何解决