Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start H2 WebServer using Spring without XML?

Tags:

java

spring

h2

I am currently using all Spring configurations as annotation and I would like to translate the following to it:

<bean id="h2Server" class="org.h2.tools.Server" factory-method="createTcpServer" init-method="start" destroy-method="stop" depends-on="h2WebServer">
    <constructor-arg value="-tcp,-tcpAllowOthers,-tcpPort,9092"/>
</bean>
<bean id="h2WebServer" class="org.h2.tools.Server" factory-method="createWebServer" init-method="start" destroy-method="stop">
    <constructor-arg value="-web,-webAllowOthers,-webPort,8082"/>
</bean>

Using the above configuration works perfectly, but since I have nothing else configured using XMLs, I would like to change it as well.

Can anyone please help me with this issue?

EDIT: Using the answer provided, this is the end result:

@Bean(name = "h2WebServer", initMethod="start", destroyMethod="stop")
public org.h2.tools.Server h2WebServer() throws SQLException {
    return org.h2.tools.Server.createWebServer("-web", "-webAllowOthers", "-webPort", "8082");
}


@Bean(initMethod="start", destroyMethod="stop")
@DependsOn(value = "h2WebServer")
public org.h2.tools.Server h2Server() throws SQLException {
    return org.h2.tools.Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9092");
}
like image 861
dambros Avatar asked May 26 '26 13:05

dambros


1 Answers

You can rewrite your XML bean definitions using the @Bean annotation style in Java, as documented in Java-based container configuration.

For example:

@Bean(init-method="start", destroy-method="stop")
public org.h2.tools.Server h2WebServer() {
   return org.h2.tools.Server.createWebServer(
      "-web", "-webAllowOthers", "-webPort", "8082"
   )
}

The doc link above will show you how to wire your two beans together, and how to add it to the Spring context.

like image 154
skaffman Avatar answered May 30 '26 03:05

skaffman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!