我们都知道,springboot项目启动时会默认把classpath目录下的application.properties文件作为系统配置文件,但如果我们想根据自己的意愿加载别的文件,比如beans.xml、config.xml等等。
设想一个场景,项目中有四个环境的配置,如开发、测试、压测和生产,分别对应下图中标识的四个文件,通过application.properties中的spring.profiles.active属性来指定不同的环境。比如spring.profiles.active=dev说明项目启动时读取的是application-dev.properties中的配置。
但是,在某种情况下我们不想通过spring.profiles.active来决定加载哪个文件,那么怎么做呢?
可通过下面的代码实现:
@SpringBootApplication
public class SpringbootTestApplication {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
//这里指定加载的是application-uat.properties文件的配置
InputStream inputStream = SpringbootTestApplication.class.getClassLoader().getResourceAsStream("application-uat.properties");
properties.load(inputStream);
SpringApplication app = new SpringApplication(SpringbootTestApplication.class);
app.setDefaultProperties(properties);
app.run(args);
}
}
但是,仅仅这样做还不够,我们要把application.properties文件名字修改一下,如果不修改那么无论程序怎么改动,默认加载的还是application.properties文件。