java - 仅在使用基于 Spring java 的配置运行测试时初始化数据库

标签 java database spring configuration h2

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

最佳答案

您可以为此使用@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
    }
}

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

关于java - 仅在使用基于 Spring java 的配置运行测试时初始化数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20227517/

相关文章:

java - 如何使用链表进行选择排序

java - 如何在 editText 中禁用 "copy/cut/paste/"工具栏,但仍然有光标选择一些文本?

java - 当我扩展 ZuulServlet 时,正在调用 Servlet 的服务和 init 方法,但没有调用 doGet

java - Spring Data Elasticsearch将Elasticsearch聚合查询转换为代码

java - Spark DataSet 有效获取整行的长度大小

mysql - 基数困惑

数据库约束——保留还是忽略?

database - 使用 ROWNUM 的 Oracle 数据库问题

java - spring mvc 项目中属性文件的位置

java - 不使用正则表达式从查询字符串中删除一个参数