Friday, 15 June 2012

Getting Spring WebApplicationContext object in Spring non managed bean

In spring non managed bean its difficult to initialize the object using the spring framework. For this either you can use

ApplicationContext context = new ClassPathXmlApplicationContext("springapp-servlet.xml");

but using the above code loads the springapp-servlet.xml once again in the memory. In case of standalone application the above code will be fine but in case its a application running on server, loading the xml again will be costlier.So for getting the Spring WebApplicationContext object you can do as code marked in colored background. 


package com.lntinfotech.office.common;


import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.lntinfotech.office.dao.DAOImpl;
import com.lntinfotech.office.dao.DAOIntf;
import com.lntinfotech.office.domain.JiraTicket;

public class DWRImpl {
private Logger logger = LoggerFactory.getLogger(getClass());

public List<JiraTicket> jiraTicketDetails(String jiraTicket,
HttpServletRequest req, HttpServletResponse res) {
logger.debug("--> jiraTicketDetails(String name)  " + jiraTicket);
List<JiraTicket> list = new ArrayList<JiraTicket>();
try {
WebApplicationContext applicationContext = WebApplicationContextUtils
.getRequiredWebApplicationContext(req.getSession()
.getServletContext());

logger.debug("--> applicationContext   " + applicationContext);

DAOIntf daoIntf = (DAOImpl) applicationContext.getBean("daoIntf");
                        /* the above code gets the DAOImpl object via Spring IOC
                        * and its initializes all the other objects mapped in the spring                              WebApplicationContext
                        * removed unwanted code from the method......
                        */
} catch (Exception e) {
logger.error("Error   : ", e);
return null;
}
logger.debug("<-- jiraTicketDetails(String name)");
return list;
}

}

No comments:

Post a Comment