Monday, July 7, 2008

Grid As A Spring Bean

We have been getting many requests about fully wiring GridGain from Spring using dependency injection. Up until now, GridGain was configured from Spring, but to get an instance of Grid you had to call GridFactory directly.

For example, one way to configure GridGain is as follows:


Grid grid = GridFactory.start(String configPath)

GridTaskFuture future = grid.execute(MyTask.class, myArg);

where configPath is path to Spring XML configuration file containing GridConfigurationAdapter bean. However this approach requires invocation of a static factory method and made it very inconvenient to reference the whole Grid instance from within other Spring beans.

With GridGain 2.1, which is planned for release within 2-3 weeks, we added GridSpringBean which is a fully initialized instance of Grid. Here is how configuration will look like:

<!-- Example of bean definition with given configuration. -->
<bean id="mySpringBean" class="org.gridgain.grid.GridSpringBean"
scope="singleton">
<property name="configuration">
<bean id="grid.cfg" class="org.gridgain.grid.GridConfigurationAdapter"
scope="singleton">
<property name="gridName" value="mySpringGrid"/>
</bean>
</property>
</bean>

The above example still configures GridConfigurationAdapter (with all defaults, that's why it's empty), however now this adapter is part of GridSpringBean which implements Grid interface. Note that by virtue of implementing InitializngBean and DisposableBean interfaces from Spring, the grid will be automatically started and stopped whenever ApplicationContext is initialized or destroyed.

Here is an example of how it could be used:

AbstractApplicationContext ctx = new FileSystemXmlApplicationContext(
"/path/to/spring/file");

// We register Spring shutdown hook to provide
// automatic beans destruction by Spring.
ctx.registerShutdownHook();

// Get Grid from Spring.
Grid grid = (Grid)ctx.getBean("mySpringBean");

// Execute your task.
GridTaskFuture<Integer> future = grid.execute(MyTask.class, myArg);

// Wait for task completion.
future.get();

Enjoy!

 

No comments: