下面2个不一样的类实现了同一个接口,@Profile注解指定了具体环境java
// 接口定义 public interface SendMessage { // 发送短信方法定义 public void send(); } // Dev 环境实现类 @Component @Profile("dev") public class DevSendMessage implements SendMessage { @Override public void send() { System.out.println(">>>>>>>>Dev Send()<<<<<<<<"); } } // Stg环境实现类 @Component @Profile("stg") public class StgSendMessage implements SendMessage { @Override public void send() { System.out.println(">>>>>>>>Stg Send()<<<<<<<<"); } } // 启动类 @SpringBootApplication public class ProfiledemoApplication { @Value("${app.name}") private String name; @Autowired private SendMessage sendMessage; @PostConstruct public void init(){ sendMessage.send();// 会根据profile指定的环境实例化对应的类 } }
在启动程序的时候经过添加 –spring.profiles.active={profile} 来指定具体使用的配置
例如咱们执行 java -jar demo.jar –spring.profiles.active=dev 那么下面三个文件中的内容将被如何应用?
Spring Boot 会先加载默认的配置文件,而后使用具体指定的profile中的配置去覆盖默认配置。spring
application.propertiesapp
app.name=MyApp server.port=8080 spring.profiles.active=dev
application-dev.propertieside
server.port=8081
application-stg.propertiescode
server.port=8082