5

I am working on 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?

Nizamuddin Shaikh
  • 383
  • 1
  • 4
  • 13

2 Answers2

4

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:

login.jsp


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

2

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.

Angelo Immediata
  • 6,635
  • 4
  • 33
  • 65