首先回忆一下在没有使用SpringBoot之前也就是传统的spring项目中是如何读取配置文件,通过I/O流读取指定路径的配置文件,然后再去获取指定的配置信息。
传统项目读取配置方式
读取xml配置文件
public String readFromXml(String xmlPath, String property) { SAXReader reader = new SAXReader(); Document doc = null; try { doc = reader.read(new File(xmlPath)); } catch (DocumentException e) { e.printStackTrace(); } Iterator<Element> iterator = doc.getRootElement().elementIterator(); while (iterator.hasNext()){ Element element = iterator.next(); if (element.getQName().getName().equals(property)){ return element.getTextTrim(); } } return null; }
读取.properties配置文件
public String readFromProperty(String filePath, String property) { Properties prop = new Properties(); try { prop.load(new FileInputStream(filePath)); String value = prop.getProperty(property); if (value != null) { return value; } } catch (IOException e) { e.printStackTrace(); } return null; }
SpringBoot读取配置方式
如何使用SpringBoot读取配置文件,从使用Spring慢慢演变,但是本质原理是一样的,只是SpringBoot简化配置,通过注解简化开发,接下来介绍一些常用注解。
@ImportResource注解
这个注解用来导入Spring的配置文件,是配置文件中的内容注入到配置类中,参数是一个数组,可以注入多个配置文件
代码演示:
在SpringBoot项目的resources目录下创建一个xml配置文件beans.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://ponent注解用来将配置类交给Spring容器管理
总结
SpringBoot中提供了注解代替配置文件的方式来获取项目中的配置,大大简化了开发,以上总结了常用的读取配置的方法,简单来说就是两种文件(yml和properties)几大注解(@Value,@PropertySource,@Configuration,@ConfigurationProperties,@Import,@Bean);首先要了解每个注解的使用场景后,其次根据项目实际情况来具体的使用
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。