@Profile

作用:根据不同环境加载不同配置

  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. }

@ActiveProfile

作用:单元测试时,激活指定的profile

  1. @ContextConfiguration(classes = Config.class)
  2. @ActiveProfiles("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会被加载到。