问题
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