View Javadoc
1   /*
2    *    Copyright 2009-2023 the original author or authors.
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    *       https://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.mybatis.guice.datasource.helper;
17  
18  import static com.google.inject.name.Names.named;
19  
20  import com.google.inject.Injector;
21  import com.google.inject.Key;
22  
23  import jakarta.inject.Inject;
24  import jakarta.inject.Provider;
25  
26  final class KeyResolver implements Provider<String> {
27  
28    private final Key<String> key;
29  
30    private final String defaultValue;
31  
32    private final String toString;
33  
34    @Inject
35    private Injector injector;
36  
37    public KeyResolver(final String key, final String defaultValue) {
38      this.key = Key.get(String.class, named(key));
39      this.defaultValue = defaultValue;
40      toString = "${" + key + "}";
41    }
42  
43    public void setInjector(Injector injector) {
44      this.injector = injector;
45    }
46  
47    /**
48     * {@inheritDoc}
49     */
50    @Override
51    public String get() {
52      try {
53        return injector.getInstance(key);
54      } catch (Throwable e) {
55        if (defaultValue != null) {
56          return defaultValue;
57        }
58        return toString;
59      }
60    }
61  
62    @Override
63    public String toString() {
64      return toString;
65    }
66  
67  }