1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.struts2.spring;
19
20 import javax.servlet.ServletContext;
21
22 import org.apache.commons.logging.Log;
23 import org.apache.commons.logging.LogFactory;
24 import org.apache.struts2.StrutsConstants;
25 import org.apache.struts2.config.Settings;
26 import org.apache.struts2.util.ObjectFactoryInitializable;
27 import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
28 import org.springframework.context.ApplicationContext;
29 import org.springframework.web.context.support.WebApplicationContextUtils;
30
31 import com.opensymphony.xwork2.spring.SpringObjectFactory;
32
33
34
35 /***
36 * Struts object factory that integrates with Spring.
37 * <p/>
38 * Spring should be loaded using a web context listener
39 * <code>org.springframework.web.context.ContextLoaderListener</code> defined in <code>web.xml</code>.
40 *
41 */
42 public class StrutsSpringObjectFactory extends SpringObjectFactory implements ObjectFactoryInitializable {
43 private static final Log log = LogFactory.getLog(StrutsSpringObjectFactory.class);
44
45
46
47
48 public void init(ServletContext servletContext) {
49 log.info("Initializing Struts-Spring integration...");
50
51 ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
52 if (appContext == null) {
53
54 String message = "********** FATAL ERROR STARTING UP SPRING-STRUTS INTEGRATION **********\n" +
55 "Looks like the Spring listener was not configured for your web app! \n" +
56 "Nothing will work until WebApplicationContextUtils returns a valid ApplicationContext.\n" +
57 "You might need to add the following to web.xml: \n" +
58 " <listener>\n" +
59 " <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>\n" +
60 " </listener>";
61 log.fatal(message);
62 return;
63 }
64
65 this.setApplicationContext(appContext);
66
67 String autoWire = Settings.get(StrutsConstants.STRUTS_OBJECTFACTORY_SPRING_AUTOWIRE);
68 int type = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;
69 if ("name".equals(autoWire)) {
70 type = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;
71 } else if ("type".equals(autoWire)) {
72 type = AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE;
73 } else if ("auto".equals(autoWire)) {
74 type = AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT;
75 } else if ("constructor".equals(autoWire)) {
76 type = AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR;
77 }
78 this.setAutowireStrategy(type);
79
80 boolean useClassCache = "true".equals(Settings.get(StrutsConstants.STRUTS_OBJECTFACTORY_SPRING_USE_CLASS_CACHE));
81 this.setUseClassCache(useClassCache);
82
83 log.info("... initialized Struts-Spring integration successfully");
84 }
85 }