01 /*
02 * Copyright 2008-2017 the original author or authors.
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.codehaus.griffon.runtime.util;
17
18 import griffon.core.injection.Injector;
19 import griffon.exceptions.InstanceNotFoundException;
20 import griffon.util.Instantiator;
21
22 import javax.annotation.Nonnull;
23 import javax.annotation.PostConstruct;
24 import javax.inject.Inject;
25 import javax.inject.Provider;
26
27 import static griffon.util.GriffonClassUtils.invokeAnnotatedMethod;
28 import static java.util.Objects.requireNonNull;
29
30 /**
31 * @author Andres Almiray
32 * @since 2.10.0
33 */
34 public class DefaultInstantiator implements Instantiator {
35 private final Provider<Injector> injector;
36
37 @Inject
38 public DefaultInstantiator(@Nonnull Provider<Injector> injector) {
39 this.injector = requireNonNull(injector, "Argument 'injector' must not be null");
40 }
41
42 @Override
43 public <T> T instantiate(@Nonnull Class<? extends T> klass) {
44 Injector injector = this.injector.get();
45
46 if (injector != null) {
47 try {
48 return (T) injector.getInstance(klass);
49 } catch (InstanceNotFoundException e) {
50 return newInstanceFromClass(klass);
51 }
52 } else {
53 return newInstanceFromClass(klass);
54 }
55 }
56
57 @Nonnull
58 protected <T> T newInstanceFromClass(@Nonnull Class<? extends T> klass) {
59 try {
60 T instance = klass.newInstance();
61 Injector injector = this.injector.get();
62 if (injector != null) {
63 injector.injectMembers(instance);
64 invokeAnnotatedMethod(instance, PostConstruct.class);
65 }
66 return instance;
67 } catch (InstantiationException | IllegalAccessException e) {
68 throw new IllegalStateException(e);
69 }
70 }
71 }
|