Start the H2 database in server mode via Spring

2020-02-08 08:49发布

I'm trying to start the H2 database in server mode (I want it to run in a different process) via Spring. Currently I'm using java Runnable.exec to start the h2 database (using the command: "java -cp h2.jar org.h2.tools.Server")

I know that there is a way to do it via Spring. I tried to add the following to the spring configuration, but it didn't work (it didn't start the H2 database):

    <bean id="org.h2.tools.Server" class="org.h2.tools.Server"
        factory-method="createTcpServer" init-method="start" destroy-method="stop">
        <constructor-arg value="-tcp,-tcpAllowOthers,true,-tcpPort,8043" />
    </bean>

    <bean id="org.h2.tools.Server-WebServer" class="org.h2.tools.Server"
        factory-method="createWebServer" init-method="start">
        <constructor-arg value="-web,-webAllowOthers,true,-webPort,8082" />
    </bean>

I would appreciate any help/ideas

3条回答
贪生不怕死
2楼-- · 2020-02-08 09:07

Are you sure the createTcpServer method in the Server class is really called? Have you tried setting up a breakpoint there?

H2 tutorial claims this how you can create and start the server programmatically:

import org.h2.tools.Server;
...
// start the TCP Server
Server server = Server.createTcpServer(args).start();
...
// stop the TCP Server
server.stop();

Your Spring definition seems to mimick the same initialization. But you can always try doing it manually - maybe it's some fault in Spring configuration.

EDIT:

I've tried your configuration and it works for me. What makes you think the server is not started? It doesn't print out anything on stdout, however the process listens at the 8043 port. So it seems pretty OK.

查看更多
【Aperson】
3楼-- · 2020-02-08 09:10

Do you happen to have:

<beans default-lazy-init="true" ...

in your Spring configuration files?

查看更多
等我变得足够好
4楼-- · 2020-02-08 09:13

Recently I had to do the same configuration to make unit test and check data, this works for me (Spring 3.1.4). Then you just have to connect with jdbc:h2:tcp://localhost:8043/mem:test and make sure to put a while(true){} at the end of your test.

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="org.h2.Driver"/>
    <!--property name="url" value="jdbc:h2:mem:;TRACE_LEVEL_FIlE=4"/-->
    <property name="url" value="jdbc:h2:mem:test;DB_CLOSE_DELAY=-1"/>
    <property name="username" value="sa"/>
    <property name="password" value=""/>
</bean>
<bean class="org.h2.tools.Server" factory-method="createTcpServer" init-method="start" destroy-method="stop">
    <constructor-arg>
        <array>
            <value>-tcp</value>
            <value>-tcpAllowOthers</value>
            <value>-tcpPort</value>
            <value>8043</value>
        </array>
    </constructor-arg>
</bean>
查看更多
登录 后发表回答