本篇文章的主题是:在SpringBoot项目中,如何读取自定义配置文件?
基于SpringBoot版本,读取自定义配置文件有以下2种方案:
- 基于SpringBoot 2.x,使用@PropertySource和@ConfigurationProperties共同标注一个JavaBean
- 基于SpringBoot 2.0以下,使用@ConfigurationProperties标注JavaBean
具体,参见下方示例:
在类路径下的config文件夹下新建jdbc.properties文件,配置项如下:
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true jdbc.userName=root jdbc.password=root
接着,创建JavaBean作为以上配置项的数据载体:
- 基于SpringBoot 2.x
@Configuration @ConfigurationProperties(prefix = "jdbc") @PropertySource("classpath:config/jdbc.properties")public class JdbcConfig { private String driverClassName; private String url; private String userName; private String password; // 省略Getter、Setter }
- 基于SpringBoot 2.0以下版本
@Configuration @ConfigurationProperties(prefix = "jdbc