控制profile生效的两种方式
@SpringBootApplication
public class App {
public static void main(String[] args) {
//使用默认profile ConfigurableApplicationContext context=SpringApplication.run(App.class, args);
//System.out.println(context.getEnvironment().getProperty("localhost"));
//System.out.println(context.getEnvironment().getProperty("girlfriend"));
SpringApplication app=new SpringApplication(App.class);
// app.setAdditionalProfiles("test");
//1、在此修改 通过设置参数来配置profile
ConfigurableApplicationContext context = app.run(args);
System.out.println(context.getEnvironment().getProperty("localhost"));
context.close();
}
}
//2、修改启动参数 --spring.profiles.active=test,dev
注解激活profile装配bean
@SpringBootApplication
//也可以给类进行装配 profile(“test”)
public class MyConfig {
@Bean
public Runnable createRunnable() {
System.out.println("11111111111111");
return ()->{};
}
@Bean
@Profile("test")
public Runnable createRunnable2() {
System.out.println("2222222222222222");
return ()->{};
}
@Bean
@Profile("dev")
public Runnable createRunnable3() {
System.out.println("3333333333333333");
return ()->{};
}
}
加载外部配置文件
package com.lsq.springboot;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.stereotype.Component;
@Component
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
try {
InputStream input=new FileInputStream("/users/qiqi/desktop/abc.properties");
Properties source=new Properties();
source.load(input);
PropertiesPropertySource propertySource=new PropertiesPropertySource("mine", source);
environment.getPropertySources().addLast(propertySource);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
org.springframework.boot.env.EnvironmentPostProcessor=com.lsq.springboot.MyEnvironmentPostProcessor