View Javadoc

1   /*
2    * Copyright 2007 Tim Peierls
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
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      {
33          this.injector = getInjector();
34      }
35  
36  
37      /**
38       * Specified via {@link org.directwebremoting.annotations.RemoteProxy @RemoteProxy}
39       * or via a parameter in XML configuration.
40       */
41      @Override public void setClass(String classname)
42      {
43          try
44          {
45              // Don't use LocalUtil.classForName because it insists
46              // on a default constructor, and we want to be able to
47              // use an @Inject constructor.
48              this.type = Class.forName(classname);
49          }
50          catch (ClassNotFoundException ex)
51          {
52              throw new IllegalArgumentException(String.format(
53                  "GuiceCreator: class %s not found", classname));
54          }
55      }
56  
57      /**
58       * The class named through {@link GuiceCreator#setClass setClass}.
59       */
60      @Override public Class getType()
61      {
62          return type;
63      }
64  
65      /**
66       * Looks up an instance of this creator's type with an
67       * {@link com.google.inject.Injector Injector}.
68       */
69      @Override public Object getInstance()
70      {
71          return injector.getInstance(type);
72      }
73  
74  
75      /**
76       * The type of object being created.
77       */
78      private volatile Class type;
79  
80      /**
81       * The Injector with which objects are created.
82       */
83      private final Injector injector;
84  }