Saturday, August 21, 2010

Spring: Creating Automatic Proxy And Applying Advice

Spring provides comprehensive Aspect Oriented Programming (AOP) support. Without going into details of Spring AOP, an Advice can be broadly defined as an action taken during execution of a method.

In my previous blog entry, I have explained hibernate interceptor which uses spring's proxy objects to intercept method execution. Similarly Spring facilitates AOP advice by creating a proxy to intercept method execution and then calling the advice logic.

Spring provides various advices types which can be applied around a method execution. Some examples are : Before Return Advice, After Return Advice, After Throwing Advice, After Finally Advice etc.

One way to automatically intercept method execution on one or more objects and then apply an advice is to use Spring's BeanNameAutoProxyCreator and Advice API.

Following is an example where we create an AfterReturningAdvice, which is called when a target bean's method returns successfully.


public class HibernateAdvice implements AfterReturningAdvice {

@Override
public void afterReturning(Object arg0, Method arg1, Object[] arg2,
Object arg3) throws Throwable {
}
}



And here is how above advice can be applied to a set of beans. In this example all methods of all the beans, whose name ends with Dao will have above advice applied.


<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames" value="*Dao"/>
<property name="interceptorNames">
<list>
<value>hibernateAdvice</value>
</list>
</property>
</bean>
<bean id="hibernateAdvice" class="com.example.HibernateAdvice"/>


Note that interceptorNames can be an advice type as shown above or an advisor. An advisor will allow more fine grained control on how a specific advice should be applied. (For example apply advice only on selected methods of a bean etc)
Promote your blog

Saturday, August 14, 2010

Spring: Using Hibernate Interceptor

Hibernate is a powerful OR framework and works really well with Spring. In Hibernate you define your entities and queries in HQL (you could also have native SQL). Most of the heavy lifting is done by Hibernate but sometimes you may need to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded. For example you may want to dynamically change the SQL generated by Hibernate.

Hibernate Interceptor:
Enter Hibernate Iterceptor. Hibernate Iterceptor provides an API which one can implement to intercept various operation like save and delete of an entity.

Typically it is better to extend EmptyInterceptor and override the methods which you want to implement.


public class HibernateInterceptor extends EmptyInterceptor {
   /* (non-Javadoc)
    * @see org.hibernate.EmptyInterceptor#onPrepareStatement(java.lang.String)
    *
    @Override
    public String onPrepareStatement(String sql) {
    }
}


Spring Hibernate Interceptor:

In Spring you can easily use easily use Hibernate Interceptor by using AnnotationSessionFactoryBean or super class LocalSessionFactoryBean which defines setEntityInterceptor(org.hibernate.Interceptor entityInterceptor) API. Here is an example of how to use it in Spring xml configuration.



<!-- Define an Interceptor -->

<bean id="myInterceptor" class="com.example.HibernateInterceptor"/>

<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" >    
    <property name="dataSource" ref="myDataSource"/>

    <!-- Refer to Interceptor Here -->
    <property name="entityInterceptor">
        <ref bean="myInterceptor"/>
    </property>

    <property name="mappingResources">
        <value>example/persistence/hibernate/customer-dao-named-queries.hbm.xml</value>
    </property>

    <property name="annotatedClasses">
    <!-- fully qualified model class names -->
        <value>com.example.persistence.model.Customer</value>
    </property>

    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>





Promote your blog

Thursday, August 5, 2010

Spring: Enabling Multipart Form Upload Http Request Processing

In Spring you can write http controller using @Controller annotation at class level to process http requests. The methods defined in controller can take HttpServletRequest as one of the arguments.


@Controller
@RequestMapping("/customers")
class CustomerController {

    @RequestMapping(method = RequestMethod.POST)
    public void postCustomer(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //processing code goes here
    }
}


Handling Form Multipart Request:

If you like to handle form multipart requests, spring provides an easy way to handle this by using MultipartHttpServletRequest. This allows you to access multipart files available in the request.

To use MultipartHttpServletRequest, you can specify CommonsMultipartResolver bean in your spring xml configuration file.


<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
</bean>


Once you specify you can change the signature of your controller methods to use
MultipartHttpServletRequest in place of HttpservletRequest:


@Controller
@RequestMapping("/customers")
class CustomerController {

    @RequestMapping(method = RequestMethod.POST)
    public void postCustomer(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
        //processing code goes here
    }
}


Promote your blog