mybatis を使うようになってから、過去、SqlSession インスタンス生成を
以下のように任せてきた。
http://blog.zaq.ne.jp/oboe2uran/article/458/
http://blog.zaq.ne.jp/oboe2uran/article/459/
http://blog.zaq.ne.jp/oboe2uran/article/460/
これらはMethod アノテーションでAOPで管理され、継承による SqlSession 取得が
魅力だった。
しかし、SqlSessionFactory をインジェクトしたい場合もあるはずだ。
import javax.inject.Provider;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.google.inject.AbstractModule;
/**
* SqlSessionFactoryModule
*/
public final class SqlSessionFactoryModule extends AbstractModule
implements Provider<SqlSessionFactory>{
final String configXmlPath;
public SqlSessionFactoryModule(){
this.configXmlPath = "Configuration.xml";
}
public SqlSessionFactoryModule(String configXmlPath){
this.configXmlPath = configXmlPath;
}
@Override
protected void configure(){
binder().bind(SqlSessionFactory.class).toProvider(this.getClass());
}
@Override
public SqlSessionFactory get(){
try{
return new SqlSessionFactoryBuilder()
.build(Resources.getResourceAsReader(getConfigXmlPath()));
}catch(Exception e){
throw new RuntimeException(e.getMessage(),e);
}
}
protected String getConfigXmlPath(){
return this.configXmlPath;
}
}