Archive

Posts Tagged ‘spring’

Loading Spring Context from Google Guice

September 15th, 2009 Shrihari No comments

Using Spring framework in any application opens a plethora of opportunities with regard to resolving complex requirement needs in lieu of the number of extensible components available based on the Spring framework. Some of the most preferred specification based stacks (such as Apache CXF)  are coupled with Spring Framework, and it would call for a need to figure out options of getting the best of breed application stacks.

This particular entry looks at loading Spring Framework from Google Guice container. There are two approaches I have across till now, which I will try covering in breif:

1) Using Guice’s SpringIntegration

In this approach you need to download guice-spring.jar (version 1.0) or if your project is maven based, add the following dependency.

<dependency>
     <groupId>com.google.inject.integration</groupId>
     <artifactId>guice-spring</artifactId>
     <version>1.0</version>
</dependency>

You need to generalize an AbstractModule and use the com.google.inject.spring.SpringIntegration to load the Spring context into the Guice’s container.

import com.google.inject.spring.SpringIntegration;
import com.google.inject.AbstractModule;
//other imports...
public class SpringContextModule extends AbstractModule
{ @Override
   protected void configure()
   { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("appcontext-config.xml");
     SpringIntegration.bindAll(binder(), applicationContext);
    }
}

2) Using GuiceyFruit’s SpringModule

In this approach,  the dependency injection is based on JSR-250 common annotations specification and is resolved using the Spring annotation @Autowired (i.e.) all the beans have to be modified, introducing the annotation wherever the injection is required. This approach is suitable for all the beans for which we have control on the source code, and may not be a viable option for integration proven Spring modular components. In case if you have maven project, you need to include the below dependency:

 <dependency>
      <groupId>org.guiceyfruit</groupId>
      <artifactId>guiceyfruit-spring</artifactId>
      <version>2.0-beta-6</version>
    </dependency>

and create a Guice injector using

Injector injector = Guice.createInjector(new SpringModule());

More details can be looked at Guicey-Spring integration wiki page.

Approach 1 is prefered for integration of various most commonly used module component common both between Guice and Spring, as the configuration context can be reused, while the other approach is good enough for custom modules in Spring to be injected in Google Guice.

Chaining Apache CXF, JackRabbit using SpringModules

September 11th, 2009 Shrihari No comments

Apache CXF integration with Spring and SpringModules support for Apache JackRabbit provides a nice combination for chaining command of actions to be delegated across layers of the enterprise application tiers . Here is a quick tip as how to do this. A more detailed tutorial has been hosted at http://bit.ly/TmmJx

1) Web application configuration (/WEB-INF/web.xml) snippet (as specified below) loads Apache CXF configuration (classpath:cxf.xml) and delegates to CXF container

<context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>classpath:cxf.xml</param-value>
 </context-param>

 <servlet>
 <servlet-name>CXFServlet</servlet-name>
 <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
 <servlet-name>CXFServlet</servlet-name>
 <url-pattern>/service/*</url-pattern>
 </servlet-mapping>

2) Apache CXF’s configuration (cxf.xml) loads the Spring context configuration

 <import resource="classpath:META-INF/cxf/cxf.xml" />
 <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
 <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
 <import resource="classpath:jcrcontext.xml"/>

where the SpringModules JCRContext configuration loads the JackRabbit’s RepositoryFactoryBean

<bean id="repository" class="org.springmodules.jcr.jackrabbit.RepositoryFactoryBean">
  <property name="configuration" value="classpath:repository.xml"/>
  <property name="homeDir" ref="./target/myrepository"/>
 </bean>

 <bean id="sessionFactory"  class="org.springmodules.jcr.jackrabbit.JackrabbitSessionFactory">
  <property name="repository" ref="repository" />
  <property name="credentials" ref="simpleCredentials"/>
 </bean>

 <bean id="jcrTemplate" class="org.springmodules.jcr.JcrTemplate">
  <property name="sessionFactory" ref="sessionFactory" />
  <property name="allowCreate" value="true" />
 </bean>

 <bean id="simpleCredentials" class="javax.jcr.SimpleCredentials">
  <constructor-arg index="0" value="bogus"/>
  <constructor-arg index="1">
   <bean factory-bean="password" factory-method="toCharArray"/>
  </constructor-arg>
 </bean>

 <bean id="password"  class="java.lang.String">
  <constructor-arg index="0" value="pass"/>
 </bean>

This chaining can be extended to any depth and a myriad range of implementation stacks could be acheived, if a container (Spring, Seam, Guice) offer support for seamless intra-container configuration and component resolution.

Using enums in DWR to populate select or multi-select

July 6th, 2009 Shrihari No comments

In case we need to population enumeration data in combo  box or multi-select widgets, in DWR (integrated on Spring), following is the approach:

1) In the spring’s applicationContext.
a) Add the method which returns the enum entity to <dwr:remote>
b) Add a dwr:convert tag of type ‘enum’ (as below)

<dwr:remote javascript="myoperations">
   <dwr:include method="getDataAsEnum"/>
   <dwr:convert type="enum"/>
</dwr:remote>

2) In the view (jsp) file, you could invoke the following javascript function

<body onload="loadEnumeration();">
function loadEnumeration()
{ myOperations.getDataAsEnum(callbackFunctionHandle);
};
var callbackFunctionHandle = function(data)
{   dwr.util.removeAllOptions('enum_select');
     dwr.util.addOptions('enum_select',['--Select--']);
     dwr.util.addOptions('enum_select', data);
}
Categories: Uncategorized Tags: ,

Implementing a Unitils DAO testing infrastructure for Spring and JPA on TestNG

June 29th, 2009 Shrihari No comments

Unitils provides an excellant infrastructure for unit testing DAO (and data-service) layers  for Spring as IoC Framework on all the component unit testing frameworks such as JUnit 3, JUnit4 and TestNG, without any boilerplate code or coniguration hassles. We will look at establishing a testing infrastructure for Spring with JPA on TestNG frmaework.

Suppose the custom DAO and its implementation definition are like this (with regard to semantics of Spring JPA integration)

package mypackage;
public CustomDAO
{    public List findAll();
     public void save(Entity eo);
}
package mypackage;
public CustomDAOImpl implements CustommmDAO
{   @PersistenceContext
    private EntityManager em;
    //all other method implementations..
      ....
}

In order to setup a Unitils test infrastructure on TestNG, the following is the class-template:

public class CustomDAOTestCase extends UnitilsTestNG
{   /**
     * Injects a test specific application context configuration
     */
    @SpringApplicationContext
    public ConfigurableApplicationContext createApplicationContext()
    {  return new ClassPathXmlApplicationContext("applicationContext-test.xml");
    }
     @SpringBean("customDAO")
     private CustomDAO customDAO;
     //all @Test annotated methods..
      @Override
      protected void unitilsAfterTestTearDown(java.lang.reflect.Method method)
      {}
}

for which the following would be the test specific Spring’s application context confguration (applicationContext-test.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 <bean id="entityManagerFactory" >
 <property name="persistenceXmlLocation" value="persistence-test.xml"/>
 <property name="persistenceUnitName" value="customservice-test"/>
 </bean>

 <bean id="transactionManager">
 <property name="entityManagerFactory" ref="entityManagerFactory" />
 </bean>

 <tx:annotation-driven />

 <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

 <bean id="customDAO" class="mypackage.CustomDAOImpl"/>
</beans>

Look specifically at entityManagerFactory bean definition, org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean allows us to load test specific persistence.xml which could allow us to maintain more than onne persistence context for a sample application.
These two definitions extend the Spring’s JPA capabilities for unit testing DAO on Unitils infrastructure!

Categories: Uncategorized Tags: , ,