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