support spring in your presentation layer

Some Time we work on project that use spring wih a MVC Framework(home made, it does not support spring integration) , some times we need to write extra servlet that do what others classes can not do.

For each time, to use a spring service inside your controller, you do this in general:

ApplicationContext context =
                    WebApplicationContextUtils
                     .getWebApplicationContext(getServletContext());
Object myDao = context.getBean("daoBeanName");

The great difficulty here is that developers can sometimes forget to instantiate beans, or instantiate them in different places, making the code complex

The idea then is to factor the instantiation in one place by a single class.This idea is verysimple, let’s take a look:

1/create an annotation “@SpringServiceController” to be associated with attributes representatives your spring beans in your servlets or other mvc controller.

2/create a SpringBeanFactory class witch contains 2 statics methods

public static final void initBeans(Object obj,ServletContext scxt){...}//to init beans for your mvc controller that it doesnot extends HttpServlet
public static final void initBeans(HttpServlet servlet) {...}//to init beans inside servlet

3/ For Servlets, if you want to factorise code , create a master HttpServlet Class, overide init() and do this

public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();

SpringBeanFactory.initBeans(this);
}

So each servlet has to extend your master servlet class, or simply overide init() method for each servlet and call initBeans(this);

For your magic MVC Controller, inside constructor or intilizer methods call

SpringBeanFactory.initBeans(this,context);

Then for each call your services will be setted by Spring

For example you can write this servlet code example:

public class ServletName extends HttpServlet{
@SpringServiceController
private MySpringService  mySpringService=null;
init(){
public void init() throws ServletException {	
		super.init();
		SpringBeanFactory.initBeans(this);
	}  
public MySpringService getMySpringService(){
           return this.mySpringService;
}
public void setMySpringService(MySpringService mySpringService){
           this.mySpringService=mySpringService;
}
}

Here is the code:

Annotation Code

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author Younss AZZAYANI
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.FIELD })
public @interface SpringServiceController{}

SpringBeanFactory class code

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class SpringBeanFactory {
public static final void initBeans(Object obj,ServletContext scxt){
ApplicationContext beanContext = WebApplicationContextUtils
.getWebApplicationContext(scxt);
Class classInstance = obj.getClass();
Field[] clazzFields = classInstance.getDeclaredFields();
for (Field field : clazzFields) {

if (field.isAnnotationPresent(SpringServiceController.class)) {
String fieldName = field.getName();
String fieldType = field.getType().getSimpleName();
String setterMethodOfField = "set"
+ String.valueOf(fieldName.charAt(0)).toUpperCase()
+ fieldName.substring(1);
try {
Method setterMethod = classInstance.getMethod(
setterMethodOfField, field.getType());
setterMethod.invoke(obj, Class.forName(
field.getType().getCanonicalName()).cast(
beanContext.getBean(String.valueOf(
fieldType.charAt(0)).toLowerCase()
+ fieldType.substring(1))));
} catch (SecurityException e) {
throw new RuntimeException(e.getMessage());
} catch (NoSuchMethodException e) {
throw new RuntimeException(e.getMessage());
} catch (BeansException e) {
throw new RuntimeException(e.getMessage());
} catch (IllegalArgumentException e) {
throw new RuntimeException(e.getMessage());
} catch (IllegalAccessException e) {
throw new RuntimeException(e.getMessage());
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getMessage());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e.getMessage());
}
}
}
}
public static final void initBeans(HttpServlet servlet) {
initBeans(servlet, servlet.getServletContext());
}
Advertisements
About

A java Developer interested in Big Data,NoSQL, Functionnal and Dynamic programming

Tagged with: , ,
Posted in Java_corner

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: