View Javadoc
1   /*
2    *    Copyright 2009-2022 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;
17  
18  import static org.apache.ibatis.io.Resources.getResourceAsReader;
19  import static org.mybatis.guice.Preconditions.checkArgument;
20  
21  import java.io.IOException;
22  import java.io.Reader;
23  import java.util.Collection;
24  import java.util.Properties;
25  
26  import org.apache.ibatis.plugin.Interceptor;
27  import org.apache.ibatis.session.Configuration;
28  import org.apache.ibatis.session.SqlSessionFactory;
29  import org.apache.ibatis.session.SqlSessionFactoryBuilder;
30  import org.apache.ibatis.type.TypeHandler;
31  
32  /**
33   * Easy to use helper Module that alleviates users to write the boilerplate google-guice bindings to create the
34   * SqlSessionFactory, via XML configuration.
35   */
36  public abstract class XMLMyBatisModule extends AbstractMyBatisModule {
37  
38    private static final String DEFAULT_CONFIG_RESOURCE = "mybatis-config.xml";
39  
40    private static final String DEFAULT_ENVIRONMENT_ID = null;
41  
42    private String classPathResource = DEFAULT_CONFIG_RESOURCE;
43  
44    private String environmentId = DEFAULT_ENVIRONMENT_ID;
45  
46    private Properties properties = new Properties();
47  
48    /**
49     * Set the MyBatis configuration class path resource.
50     *
51     * @param classPathResource
52     *          the MyBatis configuration class path resource
53     */
54    protected final void setClassPathResource(String classPathResource) {
55      checkArgument(classPathResource != null, "Parameter 'classPathResource' must be not null");
56      this.classPathResource = classPathResource;
57    }
58  
59    /**
60     * Set the MyBatis configuration environment id.
61     *
62     * @param environmentId
63     *          the MyBatis configuration environment id
64     */
65    protected final void setEnvironmentId(String environmentId) {
66      this.environmentId = environmentId;
67    }
68  
69    /**
70     * Add the variables will be used to replace placeholders in the MyBatis configuration.
71     *
72     * @param properties
73     *          the variables will be used to replace placeholders in the MyBatis configuration
74     */
75    protected final void addProperties(Properties properties) {
76      if (properties != null) {
77        this.properties.putAll(properties);
78      }
79    }
80  
81    /**
82     * {@inheritDoc}
83     */
84    @Override
85    final void internalConfigure() {
86      this.initialize();
87  
88      Reader reader = null;
89      try {
90        reader = getResourceAsReader(getResourceClassLoader(), classPathResource);
91        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader, environmentId, properties);
92        bind(SqlSessionFactory.class).toInstance(sessionFactory);
93  
94        Configuration configuration = sessionFactory.getConfiguration();
95  
96        // bind mappers
97        Collection<Class<?>> mapperClasses = configuration.getMapperRegistry().getMappers();
98        for (Class<?> mapperType : mapperClasses) {
99          bindMapper(mapperType);
100       }
101 
102       // request injection for type handlers
103       Collection<TypeHandler<?>> allTypeHandlers = configuration.getTypeHandlerRegistry().getTypeHandlers();
104       for (TypeHandler<?> handler : allTypeHandlers) {
105         requestInjection(handler);
106       }
107 
108       // request injection for interceptors
109       Collection<Interceptor> interceptors = configuration.getInterceptors();
110       for (Interceptor interceptor : interceptors) {
111         requestInjection(interceptor);
112       }
113 
114       // request injection for object factory.
115       requestInjection(configuration.getObjectFactory());
116 
117       // request injection for object wrapper factory.
118       requestInjection(configuration.getObjectWrapperFactory());
119     } catch (Exception e) {
120       addError("Impossible to read classpath resource '%s', see nested exceptions: %s", classPathResource,
121           e.getMessage());
122     } finally {
123       if (reader != null) {
124         try {
125           reader.close();
126         } catch (IOException e) {
127           // close quietly
128         }
129       }
130     }
131   }
132 
133 }