您的位置:首页 > 编程语言 > Java开发

005-Spring Boot配置分析-配置文件、EnvironmentPostProcessor、Profiles

2018-01-21 22:06 836 查看

一、配置文件application

默认配置文件application.propertie或者application.yml,可同时存在

application.propertie增加配置:local.ip=192.168.1.1

application.yml增加配置【使用缩进】:

jdbc:
name: lhx


默认位置:classpath、classpath:/config、file:/、file:config下

注意:application.properties==application-default.properties

1、读取方式

方式一、context.getEnvironment().getProperty("local.ip","默认值")

View Code
需要注册到META-INF/spring.factories文件

1.增加此文件,并增加内容

org.springframework.boot.env.EnvironmentPostProcessor=com.lhx.spring.springboot_config.MyEnvironmentPostProcessor


2.增加实现类文件MyEnvironmentPostProcessor

View Code

三、Profiles

增加两个配置文件



方式一、程序读取

在application-dev.properties中添加

jdbc.url=jdbc:mysql://127.0.0.1/spring_dev


在application-test.properties中添加

jdbc.url=jdbc:mysql://127.0.0.1/spring_test


程序使用

SpringApplication app = new SpringApplication(App3.class);
app.setAdditionalProfiles("test");//test 读取application-test.properties
ConfigurableApplicationContext context = app.run(args);
context.getBean(Runnable.class).run();
System.out.println(context.getEnvironment().getProperty("jdbc.url"));
context.close();


注:可在setAdditionalProfiles配置多个,会被覆盖

方式二、参数配置

启动参数增加,多个使用逗号分割,配置多个 多个同时生效

--spring.profiles.active=test


使用

方式三、@Profile注解

@SpringBootConfiguration
public class MyConfig {
@Bean
public Runnable createRunnable() {
System.out.println("--------1--------");
return ()->{};
}

@Bean
@Profile("dev")
public Runnable createRunnable2() {
System.out.println("--------2--------");
return ()->{};
}

@Bean
@Profile("test")
public Runnable createRunnable3() {
System.out.println("--------3--------");
return ()->{};
}
}


启动对应环境时候生效
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: