有时候有这样子的情景,我们想把配置文件的信息,读取并自动封装成实体类,这样子,我们在代码里面使用就轻松方便多了。
1、@ConfigurationProperties注解默认读取主配置文件,springboot中主配置文件是application.properties和application.yml
例:
yml配置文件:
ftp:
port: 21
host: 172.0.0.1
user-name: ces
password: ces
@ConfigurationProperties(prefix = "ftp")
@Data
@Component
public class FtpEntity {
private String host;
private Integer port;
private String userName;
private String password;
}
2、@PropertySource用于读取指定的配置文件
@Data
@Configuration
@PropertySource("classpath:plat-config.properties")
public class PlatConfig {
@Value("${desKey}")
public String desKey;
}
本文介绍如何在SpringBoot项目中使用@ConfigurationProperties和@PropertySource注解,将配置文件信息自动封装成实体类,实现便捷的数据访问。通过具体示例展示了如何配置YAML和属性文件,以及如何在代码中映射这些配置。
464

被折叠的 条评论
为什么被折叠?



