springboot实体类映射配置文件_SpringBoot配置文件自动映射到属性和实体类(8)

本文介绍了如何在SpringBoot中将配置文件内容映射到实体类,包括在Controller中配置文件加载,使用@Value注解读取配置参数,实体类的@ConfigurationProperties配置,以及@Autowired自动注入,举例展示了JDBCSettings实体类的创建和jdbc.properties的配置信息,最后通过Controller获取并展示配置信息。
摘要由CSDN通过智能技术生成

一、配置文件加载

1、Controller中配置并指向文件

@Controller

@PropertySource(value= { "application.properties" })//指定配置文件

2、在变量上打注解并指明配置文件中的key

@Value("${web.upload.filepath}")//获取配置文件中的配置参数

private String filePath;

二、实体类配置文件

1、添加@Component//文件扫描注解

2、使用@PropertySource({"classpath:jdbc.properties"}) //指定配置文件的位置

3、使用@ConfigurationProperties 或者 @ConfigurationProperties(prefix="jdbc")//前缀,设置相关的属性;

4、使用@Autowired//通过IOC对象自动注入

示例-新建实体类如下:

packagecn.xiaobing.demo.pojo;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.context.annotation.PropertySource;importorg.springframework.stereotype.Component;

@Component//文件扫描

@PropertySource({"classpath:jdbc.properties"})//@ConfigurationProperties

@ConfigurationProperties(prefix="jdbc")//前缀

public classJDBCSettings {//@Value("${jdbc.driver}")//如果属性命名和配置文件中配置name一致就不需要声明@Value("${jdbc.driver}")

privateString driver;privateString url;privateString username;privateString password;publicString getDriver() {returndriver;

}public voidsetDriver(String driver) {this.driver =driver;

}publicString getUrl() {returnurl;

}public voidsetUrl(String url) {this.url =url;

}publicString getUsername() {returnusername;

}public voidsetUsername(String username) {this.username =username;

}publicString getPassword() {returnpassword;

}public voidsetPassword(String password) {this.password =password;

}publicJDBCSettings(String driver, String url, String username, String password) {super();this.driver =driver;this.url =url;this.username =username;this.password =password;

}publicJDBCSettings() {super();

}

@OverridepublicString toString() {return "JDBCSetting [driver=" + driver + ", url=" + url + ", username=" + username + ", password=" +password+ "]";

}

}

jdbc.properties文件配置信息

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/future?useUnicode=true&characterEncoding=utf-8

jdbc.username=Administrator1

jdbc.password=123456

Controller编码

@RestControllerpublic classGetController {

@Autowired//通过IOC对象自动注入进来

privateJDBCSettings jdbcSettings;

@GetMapping("/v1/getJdbcProperties")publicObject getJDBCProperties() {returnjdbcSettings;

}

}

启动项目访问:

914810c1b8100f0e83df480e5918376a.png

三、不足之处,后续补充。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值