spring boot 导入配置文件

2022年12月3日12:56:51

@ImportResource:通过locations属性加载对应的xml配置文件,同时需要配合@Configuration注解一起使用,定义为配置类;

@Configuration@ImportResource(locations = {"classpath:druid.xml","classpath:spring-mybatis.xml"})publicclassConfigDataSource {

}

@PropertySource:
value:这里指定配置文件,替代原来@ConfigurationProperties的locations
encoding:指定读取配置文件时的编码,这个encoding很重要,如果不指定使用默认的话很可能出现读取乱码的情况,
@PropertySource注解可以从properties文件中,获取对应的key-value值,将其赋予变量;

@PropertySource({"classpath:config.properties","classpath:db.properties" 
})@PropertySources({@PropertySource("classpath:config.properties"),@PropertySource("classpath:db.properties")
})@PropertySource(value= {"classpath:config/app-dev.properties"},ignoreResourceNotFound=false,encoding="UTF-8",name="app-dev.properties")

上述的代码目的是加载classpath路径中config文件中的app-dev.properties。其中encoding用于指定读取属性文件所使用的编码,我们通常使用的是UTF-8;ignoreResourceNotFound含义是当指定的配置文件不存在是否报错,默认是false;比如上文中指定的加载属性文件是app-dev.properties。如果该文件不存在,则ignoreResourceNotFound为true的时候,程序不会报错,如果ignoreResourceNotFound为false的时候,程序直接报错。实际项目开发中,最好设置ignoreResourceNotFound为false。该参数默认值为false。value值是设置需要加载的属性文件,可以一次性加载多个。name的值我们设置的是app-dev.properties。这个值在Springboot的环境中必须是唯一的,如果不设置,则值为:“class path resource [config/app-dev.properties]“。
为什么是“class path resource [config/app-dev.properties]“呢?这个就涉及到了Spring中对资源文件的封装类Resource。上文我们配置的value值为”classpath:config/app-dev.properties”,因此Spring发现是classpath开头的,因此最终使用的是Resource的子类ClassPathResource。如果是file开头的,则最终使用的类是FileSystemResource。
了解了上文所述的Resource类之后。如果@PropertySource中如果没有设置name值,则name值的生成规则是:根据value值查找到最终封装的Resource子类,然后调用具体的Resource子类实例对象中的getDescription方法,getDescription方法的返回值为最终的name值。

@ConfigurationProperties:
常用的两个属性是:
locations:指定配置文件
prefix:指定该配置文件中的某个属性群的前缀
@ConfigurationProperties(prefix ="spring.datasource.druid")  
@PropertySource( name="datasource-dev.properties",value= {"classpath:config/datasource-dev.properties"},ignoreResourceNotFound=false,encoding="UTF-8")publicclass DruidDataSourceConfig  {private  String url;
  }

指明了属性的前缀为spring.datasource.druid。这样Springboot在处理的时候,会去扫描当前类中的所有字段并进行属性的查找以及组装。比如我们配置的prefix = “spring.datasource.druid”,DruidDataSourceConfig类中的url字段,则url字段需要匹配的属性是prefix+字段=spring.datasource.druid.url。
如果指定的字段没有找到属性怎么办呢?ignoreUnknownFields:忽略未知的字段。ignoreInvalidFields:是否忽略验证失败的字段。在配置文件中配置了一个字符串类型的变量,类中的字段是int类型,那肯定会报错的。如果出现这种情况我们可以容忍,则需要配置该属性值为true。该参数值默认为false。

  • 作者:rznice
  • 原文链接:https://blog.csdn.net/rznice/article/details/82658349
    更新时间:2022年12月3日12:56:51 ,共 2251 字。