1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.seasar.cubby.plugins.guice;
17
18 import java.util.ArrayList;
19 import java.util.List;
20
21 import javax.servlet.ServletContext;
22 import javax.servlet.ServletContextEvent;
23
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 import com.google.inject.Guice;
28 import com.google.inject.Injector;
29 import com.google.inject.Module;
30 import com.google.inject.servlet.GuiceServletContextListener;
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52 public class CubbyGuiceServletContextListener extends
53 GuiceServletContextListener {
54
55 private static final Logger logger = LoggerFactory
56 .getLogger(CubbyGuiceServletContextListener.class.getName());
57
58
59 public static final String MODULE_INIT_PARAM_NAME = "cubby.guice.module";
60
61
62 private String[] moduleClassNames;
63
64
65
66
67 @Override
68 public void contextInitialized(ServletContextEvent servletContextEvent) {
69 final ServletContext servletContext = servletContextEvent
70 .getServletContext();
71 final String moduleClassNamesString = servletContext
72 .getInitParameter(MODULE_INIT_PARAM_NAME);
73 if (moduleClassNamesString == null
74 || moduleClassNamesString.length() == 0) {
75 throw new IllegalArgumentException("No context parameter \""
76 + MODULE_INIT_PARAM_NAME + "\", please set Module FQCN");
77 }
78 this.moduleClassNames = moduleClassNamesString.split(",");
79
80 super.contextInitialized(servletContextEvent);
81 }
82
83
84
85
86
87
88
89
90 protected Module createModule(final String moduleClassName) {
91 if (logger.isInfoEnabled()) {
92 logger.info("Instantiates " + moduleClassName);
93 }
94
95 final ClassLoader loader = Thread.currentThread()
96 .getContextClassLoader();
97 try {
98 final Class<?> clazz = Class.forName(moduleClassName, true, loader);
99 final Module module = Module.class.cast(clazz.newInstance());
100 return module;
101 } catch (final ClassNotFoundException e) {
102 throw new IllegalArgumentException("Illegal module "
103 + moduleClassName, e);
104 } catch (final InstantiationException e) {
105 throw new IllegalArgumentException("Illegal module "
106 + moduleClassName, e);
107 } catch (final IllegalAccessException e) {
108 throw new IllegalArgumentException("Illegal module "
109 + moduleClassName, e);
110 }
111 }
112
113
114
115
116 @Override
117 protected Injector getInjector() {
118 final List<Module> modules = new ArrayList<Module>();
119 for (final String moduleClassName : this.moduleClassNames) {
120 final Module module = createModule(moduleClassName.trim());
121 modules.add(module);
122 }
123 return Guice.createInjector(modules);
124 }
125
126 }