【问题标题】:Initialize database only when running Test using Spring java based configuration仅在使用基于 Spring java 的配置运行测试时初始化数据库
【发布时间】:2013-11-26 20:40:31
【问题描述】:

我有代码来创建数据源并运行脚本来创建模式并使用基于 java 的 spring 配置添加数据。我只想在测试模式下运行这些脚本。我需要在数据库初始化程序 bean 之上指定任何注释来完成这项工作吗?

【问题讨论】:

    标签: java database spring configuration h2


    【解决方案1】:

    您可以为此使用@profile 注解,例如:

    @Configuration
    @Profile("test_profile")
    public class StandaloneDataConfig {
    
        @Bean
        public DataSource dataSource() {
        // do data source creation/initialization
        }
    }
    

    然后使用:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(loader=AnnotationConfigContextLoader.class,
        classes={StandaloneDataConfig.class})
    @ActiveProfiles("test_profile")
    public class TransferServiceTest {
    
        @Autowired
        private TransferService transferService;
    
        @Test
        public void testTransferService() {
            // test the transferService
        }
    }
    

    您可以阅读 Spring 团队的 this 博客文章以了解更多详细信息。

    【讨论】:

    • 我可以通过使用两个单独的 Java 配置来做到这一点,但是如何使用单个 Java 配置文件来做到这一点?
    猜你喜欢
    • 1970-01-01
    • 2019-08-29
    • 2016-08-08
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多