一. 使用 SpringApplication.run 直接运行
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
默认的配置文件 application.properties 和 application.yml
2. 使用SpringApplicationBuilder指定其他配置
如果想自己指定配置文件,可以在Spring容器的启动命令中加入参数
@SpringBootApplication
public class TestDefaultFile {
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestDefaultFile.class)
//指定配置文件
.properties("spring.config.location=classpath:/test-folder/my-config.properties")
.run(args);
// 输出变量
System.out.println(context.getEnvironment().getProperty("jdbc.user"));
}
}
test-folder/my-config.properties
jdbc.user=e
@SpringBootApplication
public class TestProfiles {
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestProfiles.class)
.properties("spring.config.location=classpath:/test-profiles.yml")
.properties("spring.profiles.active=oracle")
.run(args);
// 输出变量
System.out.println(context.getEnvironment().getProperty("jdbc.driver"));
// 启动第二个Spring容器,指定端口为8848
ConfigurableApplicationContext context2 = new SpringApplicationBuilder(TestProfiles.class)
.properties("spring.config.location=classpath:/test-profiles.yml")
.properties("spring.profiles.active=mysql")
.properties("server.port=8848")
.run(args);
// 输出变量
System.out.println(context2.getEnvironment().getProperty("jdbc.driver"));
}
}
@SpringBootApplication
public class TestProfiles02 {
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestProfiles02.class)
.properties("spring.config.location=classpath:/test-profiles.yml")
//是否是web环境
.web(WebApplicationType.NONE)
//指定环境
.profiles("oracle")
.run(args);
// 输出变量
System.out.println(context.getEnvironment().getProperty("jdbc.driver"));
}
}
test-profiles.yml
spring:
profiles: mysql
jdbc:
driver:
com.mysql.jdbc.Driver
---
spring:
profiles: oracle
jdbc:
driver:
oracle.jdbc.driver.OracleDriver
@SpringBootApplication
public class TestYaml {
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestYaml.class)
.properties("spring.config.location=classpath:/my-config.yml")
.run(args);
// 输出变量
System.out.println(context.getEnvironment().getProperty("jdbc.user"));
System.out.println(context.getEnvironment().getProperty("jdbc.passwd"));
System.out.println(context.getEnvironment().getProperty("jdbc.driver"));
}
}
my-config.yml
jdbc:
user:
root
passwd:
123456
driver:
com.mysql.jdbc.Driver