「Spring MVC」JNDI と DataSourceを使ってOracleに接続する方法
環境
Spring 5.3.8 jdk 1.8
書式
1.ResourceBundle.getBundle(“プロパティファイル名")
リソース・バンドルには、ロケール固有のオブジェクトが含まれます。
ResourceBundle bundle = ResourceBundle.getBundle("AppRes");
2.getString(String key)
このリソース・バンドルまたはその親リソース・バンドルのいずれかから指定されたキーの文字列を取得します。
3.public class InitialContext extends Object implements Context
このクラスは、ネーミング操作を実行するための開始コンテキストです。ネーミング操作はすべて、コンテキストを基準にします。
4.lookup(String name)
名前付きオブジェクトを取得します。
5.public interface DataSource extends CommonDataSource, Wrapper
このDataSourceオブジェクトが表す物理データ・ソースへの接続に対するファクトリです。 getConnection() このDataSourceオブジェクトが表すデータ・ソースへの接続の確立を試みます。
6.void setAutoCommit(boolean autoCommit) throws SQLException
この接続の自動コミット・モードを指定された状態に設定します。 autoCommit - 自動コミット・モードを有効にする場合はtrue、無効にする場合はfalse
使用例
1.プロパティファイル(AppRes.ApplicationResources.properties)
db.connection=jdbc/cft
2.Java側のサンプルコード
private static String strJndi = null;
try {
if(strJndi == null){
//ResourceBundleクラスでプロパティファイルをロード
ResourceBundle bundle = ResourceBundle.getBundle("AppRes");
//キー「db.connection」の文字列を取得
strJndi = bundle.getString("db.connection");
}
//InitialContextを取得
Context initContext = new InitialContext();
//DataSource型のインスタンスを取得
DataSource ds = (DataSource) initContext.lookup(strJndi);
//DataSource型のインスタンスからConnectionを取得
Connection conn = ds.getConnection();
//自動キミット無効
conn.setAutoCommit(false);
return conn;
} catch (Exception e) {
処理コード
}
3.web.xmlの設定
<resource-ref>
<description>Oracle Datasource</description>
<res-ref-name>jdbc/cft</res-ref-name>
<res-type>javax.sql.ConnectionPoolDataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
説明
resource-ref要素: JNDIの利用を宣言しています。 res-ref-name要素: リソース参照名を記述します。 res-type要素:JNDIに格納されているコンポーネントの型を記述します。 res-sharing-scope要素:Shareableが指定されています。