Struts2 Spring Integration and Accessing ApplicationContext

Struts2 Spring Integration 
To enable Spring integration, simply include struts2-spring-plugin-x-x-x.jar in your application. 
If you are using more than one object factory, (for example, by including both the Spring and Plexus plugins in your application,) you will need to set the struts.objectFactory property in struts.properties or in one of several XML files via Constant Configuration:
struts.properties
struts.objectFactory = spring
struts.xml
<struts>
 <constant name="struts.objectFactory" value="spring" />
 ...
</struts>
  • Configure the Spring listener  -web.xml
<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

More applicationContext configuration files needed?
Since the Spring integration uses a standard Listener, it can be configured to support configuration files other than applicationContext.xml. Adding the following to your web.xml will cause Spring's ApplicationContext to be inititalized from all files matching the given pattern: 

<!-- Context Configuration locations for Spring XML files -->
<context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value>
</context-param>



Access ApplicationContext: 
Case 1: For Web Application    
 Use the Spring’s generic WebApplicationContextUtils class to get the Spring’s bean directly.

WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(
                                    ServletActionContext.getServletContext());
                UserBo userBo1 = (UserBo)context.getBean("userBo"); 
Case2: For Any Application   
(1) Add following entry in your springconfig.xml

     <bean id="applicationContext" class="com.utils.ApplicationContextUtils">
     </bean> 
(2) 
package com.utils;
import org.springframework.beans.BeansException; 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.ApplicationContextAware;   
public class ApplicationContextUtils implements ApplicationContextAware {     
        private static ApplicationContext ctx;     
        
        public void setApplicationContext(ApplicationContext appContext) throws BeansException {
                ctx = appContext;    
                }     
        public static ApplicationContext getApplicationContext() {     
                return ctx;   
                } 
}

(3) Access your object through ApplicationContextUtils 
ApplicationContext context = ApplicationContextUtils.getApplicationContext();
UserBo userBo1 = (UserBo)context.getBean("userBo");


Please leave your comments and suggestions below...

Comments

Popular posts from this blog

Ashtavinayak Temples | 8 Ganpati Temples of Maharashtra | Details Travel Reviews

Ramoji Film City, Hyderabad, India

Pune to Ganpatipule Trip