Chapter 2: Annotations - @ActiveProfiles

@ActiveProfiles可以用来在测试的时候启用某些Profile的Bean。本章节的测试代码使用了下面的这个配置:

  1. @Configuration
  2. public class Config {
  3. @Bean
  4. @Profile("dev")
  5. public Foo fooDev() {
  6. return new Foo("dev");
  7. }
  8. @Bean
  9. @Profile("product")
  10. public Foo fooProduct() {
  11. return new Foo("product");
  12. }
  13. @Bean
  14. @Profile("default")
  15. public Foo fooDefault() {
  16. return new Foo("default");
  17. }
  18. @Bean
  19. public Bar bar() {
  20. return new Bar("no profile");
  21. }
  22. }

例子1:不使用ActiveProfiles

在没有@ActiveProfiles的时候,profile=default和没有设定profile的Bean会被加载到。

源代码ActiveProfileTest

  1. @ContextConfiguration(classes = Config.class)
  2. public class ActiveProfileTest extends AbstractTestNGSpringContextTests {
  3. @Autowired
  4. private Foo foo;
  5. @Autowired
  6. private Bar bar;
  7. @Test
  8. public void test() {
  9. assertEquals(foo.getName(), "default");
  10. assertEquals(bar.getName(), "no profile");
  11. }
  12. }

例子2:使用ActiveProfiles

当使用了@ActiveProfiles的时候,profile匹配的和没有设定profile的Bean会被加载到。

源代码ActiveProfileTest

  1. @ContextConfiguration(classes = Config.class)
  2. [@ActiveProfiles][doc-active-profiles]("product")
  3. public class ActiveProfileTest extends AbstractTestNGSpringContextTests {
  4. @Autowired
  5. private Foo foo;
  6. @Autowired
  7. private Bar bar;
  8. @Test
  9. public void test() {
  10. assertEquals(foo.getName(), "product");
  11. assertEquals(bar.getName(), "no profile");
  12. }
  13. }

总结

  • 在没有@ActiveProfiles的时候,profile=default和没有设定profile的Bean会被加载到。
  • 当使用了@ActiveProfiles的时候,profile匹配的和没有设定profile的Bean会被加载到。

@ActiveProfiles同样也可以和@SpringBootTest配合使用,这里就不举例说明了。

参考文档