01: /*
02: * Copyright 2007 Tim Peierls
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.directwebremoting.guice;
17:
18: import com.google.inject.Injector;
19:
20: import org.directwebremoting.extend.Creator;
21: import org.directwebremoting.create.NewCreator;
22:
23: import static org.directwebremoting.guice.DwrGuiceUtil.getInjector;
24:
25: /**
26: * A creator that uses Guice dependency injection to create remoted objects.
27: * @author Tim Peierls [tim at peierls dot net]
28: */
29: public class GuiceCreator extends NewCreator implements Creator {
30:
31: public GuiceCreator() {
32: this .injector = getInjector();
33: }
34:
35: /**
36: * Specified via {@link org.directwebremoting.annotations.RemoteProxy @RemoteProxy}
37: * or via a parameter in XML configuration.
38: */
39: @Override
40: public void setClass(String classname) {
41: try {
42: // Don't use LocalUtil.classForName because it insists
43: // on a default constructor, and we want to be able to
44: // use an @Inject constructor.
45: this .type = Class.forName(classname);
46: } catch (ClassNotFoundException ex) {
47: throw new IllegalArgumentException(String.format(
48: "GuiceCreator: class %s not found", classname));
49: }
50: }
51:
52: /**
53: * The class named through {@link GuiceCreator#setClass setClass}.
54: */
55: @Override
56: public Class<?> getType() {
57: return type;
58: }
59:
60: /**
61: * Looks up an instance of this creator's type with an
62: * {@link com.google.inject.Injector Injector}.
63: */
64: @Override
65: public Object getInstance() {
66: return injector.getInstance(type);
67: }
68:
69: /**
70: * The type of object being created.
71: */
72: private volatile Class<?> type;
73:
74: /**
75: * The Injector with which objects are created.
76: */
77: private final Injector injector;
78: }
|