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.configuration.settings;
17  
18  import com.google.inject.Injector;
19  import com.google.inject.Key;
20  
21  import jakarta.inject.Inject;
22  import jakarta.inject.Provider;
23  
24  import org.apache.ibatis.session.Configuration;
25  import org.apache.ibatis.type.TypeHandler;
26  
27  public final class JavaTypeAndHandlerConfigurationSettingProvider implements Provider<ConfigurationSetting> {
28    @Inject
29    private Injector injector;
30  
31    private final Wrapper<?> wrapper;
32  
33    private JavaTypeAndHandlerConfigurationSettingProvider(final Wrapper<?> wrapper) {
34      this.wrapper = wrapper;
35    }
36  
37    @Override
38    public ConfigurationSetting get() {
39      return wrapper.get(injector);
40    }
41  
42    public static <T> JavaTypeAndHandlerConfigurationSettingProvider create(final Class<T> type,
43        final Key<? extends TypeHandler<? extends T>> key) {
44      return new JavaTypeAndHandlerConfigurationSettingProvider(new Wrapper<T>(type, key));
45    }
46  
47    private static class Wrapper<T> {
48      private final Class<T> type;
49      private final Key<? extends TypeHandler<? extends T>> key;
50  
51      private Wrapper(final Class<T> type, final Key<? extends TypeHandler<? extends T>> key) {
52        this.type = type;
53        this.key = key;
54      }
55  
56      ConfigurationSetting get(Injector injector) {
57        final TypeHandler<? extends T> handlerInstance = injector.getInstance(key);
58        return new ConfigurationSetting() {
59          @Override
60          public void applyConfigurationSetting(Configuration configuration) {
61            configuration.getTypeHandlerRegistry().register(type, handlerInstance);
62          }
63        };
64      }
65    }
66  }