Setting up in-memory H2 database without Spring Boot

烈酒焚心 提交于 2020-12-12 03:22:53

问题


I am working in a spring 5 (Not Sprig Boot) project. I need to test my application with in-memory H2 database. I am using Spring with Java Config on maven build tool. Is there any way I can configure in-memory H2 DB?


回答1:


Usually I use this in my @Config class:

@Bean
public DataSource h2TestDataSource(){
   return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
}

So I use Spring Embedded DB in my spring projects (I don't use spring boot)

I hope it's useful.




回答2:


You can add the DataSource bean using the EmbeddedDatabaseBuilder as follows:

@Bean
public DataSource dataSource(
        @Value("${datasource.dbname}") String dbname,
        @Value("${datasource.script}") String script) {

    return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.H2)
            .setName(dbname)
            .addScript(script)
            .build();
}

application.properties

datasource.dbname=users
datasource.script=classpath:resources/users.sql

Also you can register h2-console servlet in the application configuration class as follows:

@Configuration
public class WebAppConfig implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) {
        . . .

        servletContext
                .addServlet("H2Console", WebServlet.class)
                .addMapping("/console/*");

        . . .
    }
}

Then you can open http://localhost:8080/console and connect to the jdbc:h2:mem:users database as follows:


See also How to enable h2-console in spring-webmvc without spring-boot?



来源:https://stackoverflow.com/questions/50759853/setting-up-in-memory-h2-database-without-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!