@Profile
作用:根据不同环境加载不同配置
@Configuration
public class Config {
@Bean
@Profile("dev")
public Foo fooDev() {
return new Foo("dev");
}
@Bean
@Profile("product")
public Foo fooProduct() {
return new Foo("product");
}
@Bean
@Profile("default")
public Foo fooDefault() {
return new Foo("default");
}
@Bean
public Bar bar() {
return new Bar("no profile");
}
}
@ActiveProfile
作用:单元测试时,激活指定的profile
@ContextConfiguration(classes = Config.class)
@ActiveProfiles("product")
public class ActiveProfileTest extends AbstractTestNGSpringContextTests {
@Autowired
private Foo foo;
@Autowired
private Bar bar;
@Test
public void test() {
assertEquals(foo.getName(), "product");
assertEquals(bar.getName(), "no profile");
}
}
- 在没有@ActiveProfiles的时候,profile=default和没有设定profile的Bean会被加载到。
- 当使用了@ActiveProfiles的时候,profile匹配的和没有设定profile的Bean会被加载到。