在这里整理一下Java读取配置文件的方式,本文的环境是Springboot+ssm
1、什么是配置文件? 2、配置文件的好处? 3、怎么使用? 4、怎样使用Java进行读取?
配置文件其实可以理解位资源文件,而这个资源文件可以包含一些固定的参数,配置文件一般分为两种:Properties 和 xml形式, 存储形式:properties中的数据是键值对形式的数据,只能存储字符串形式的数据
主要的作用:解决硬编码问题。硬编码问题:也可以简单的说成是代码中写死的东西,例如:路径,一些静态资源放行,数据库的连接等等。。。。
采用键值对的形式进行填写,这里采用数据库的连接为例子:
spring.datasource.url=jdbc:postgresql://localhost:xxx/yyy spring.datasource.username=xxx spring.datasource.password=xxx spring.datasource.driver-class-name=org.postgresql.Driver代码书写步骤: 1、创建Properties类 2、采用ClassLoader加载properties配置文件对象的流 3、使用properties中的load方法加载流 4、采用properties.getProperty(String key)获取key对应的value值
Properties properties = new Properties(); InputStream in = PropertiesMain.class.getClassLoader().getResourceAsStream("config/application.properties"); properties.load(in); properties.getProperty(String key); 第二种方式:采用@ConfigurationProperties(prefix = “xxx”)读取代码书写方式、 1、按照上述的properties使用中 书写配置文件(这里分为两种:一种是application.properties,一种是自定义的xxx.properties) 2、打注解@ConfigurationProperties
@Component @ConfigurationProperties(prefix = "data-import.user.excel") @Data public class DataImportUserExcelConfig { private String userInfoImportTemplateName; private Integer cellHeadTitleRowIndex; } xxx //下面是application.properties中的这两个字段的定义 data-import.user.excel.cell-head-title-row-index=3 data-import.user.excel.user-info-import-template-name= xxx1、 @component 这个注解需要加上 2、当读取的是application.properties中的配置文件的时候,就用上述的注解 3、当读取的是自定义的配置文件的时候:需将@ConfigurationProperties(prefix = “data-import.user.excel”)注解替换为 @Configuration @ConfigurationProperties(prefix = “remote”, ignoreUnknownFields = false) @PropertySource(“classpath:config/remote.properties”) 第一个注解:表明是一个配置类 第二个注解:prefix:配置前缀 ignoreUnknownFields:匹配不到的时候抛出异常 第三个注解:指定配置文件的路径(需放在resource下)
第三种方式:采用@Value("${xx.xx}")方式进行读取代码书写格式: 1、书写的位置:可以在字段上面,也可以在方法上面(赋值给方法中的参数) 2、书写的规范:需使用在能自动注入的类中 ,在使用的过程中,不能失去spring的管理(即不能new , 以及静态变量)
@Component public class Demo1 { @Value("${data.test.k}") public String k; @Autowired private Demo1 demo1; public String get() { return k; } //配置文件中的书写 data.test.k="a,b,c"