这一个地方属于新知识,之前没有接触过,TOT的时候做的小项目也是用的springboot .yml文件直接配置数据库环境的。
我的理解就是在不同的生产阶段,初始化配置数据库的环境是有所不同的,比如迭代刚刚启动,我们使用的可能就是本地的内存数据库h2,而项目生产阶段使用的可能就是别的数据库(我并不知道生产阶段会用什么数据库.....)
package com.glodon.springdemo4;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
/**
* 貌似dev、prod这些都是可以随意调整的命名
* 但是基本约定是按照dev、prod进行命名的
*/
@Configuration
public class ProfileBean {
@Bean
@Profile("dev")
public EvnBean devEnvironment(){
System.out.println("Devlopment environment is running!");
return new EvnBean("This is development envirionment!");
}
@Bean
@Profile("prod")
public EvnBean prodEnvironment(){
System.out.println("Production environment is running!");
return new EvnBean("This is production environment!");
}
}
在配置类中指定@Profile,可以在运行时决定选择哪一种初始化环境。
写一个单元测试看下效果:
package com.glodon.springdemo4;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ProfileBean.class)
@ActiveProfiles("prod")
public class ProfileBeanTest {
@Test
public void environmentTest(){
}
}
使用@ActiveProfiles指定使用生产环境,随便写一个空的测试运行就会发现“prod” bean中的sout内容被打印了。