@Profile可以提供在开发过程中的开发环境、测试环境、准生产环境、生产环境的切换。
例如在不同的环境使用不同的数据库源。
@Profile的value值与application.properties中的配置项spring.profiles.active的值相对应。
spring.profiles.active是对启用的配置文件的名称的定义。假设我们在application.properties中配置spring.profiles.active=dev,则项目启动时就会采用application-dev.properties中的配置信息。
@Component
@Configuration
public class ProfileTest {
@Bean(name = "testBeanProfile")
@Profile("dev")
public TestBeanProfile getDevTestBean(){
System.out.println("使用dev环境");
TestBeanProfile testBean = new TestBeanProfile();
testBean.setDescribtion("34769690");
testBean.setNeme("vkjghlgkjll");
return testBean;
}
@Bean(name = "testBeanProfile")
@Profile("test")
public TestBeanProfile getTestTestBean(){
System.out.println("使用test环境");
TestBeanProfile testBean = new TestBeanProfile();
testBean.setDescribtion("rheufahd");
testBean.setNeme("fhahasjdio");
return testBean;
}
}
新建两个文件application-dev.properties和application-test.properties
在application.properties加入配置项spring.profiles.active
当spring.profiles.active=dev时启动项目:
当spring.profiles.active=dev时启动项目: