非同期 Bean メソッドは、このメソッドが作成する Java 2 Platform Enterprise Edition (J2EE) コンポーネントが java:comp リソース参照を使用して取得した接続を使用することができます
リソース参照について詳しくは、トピック参照を参照してください。以下に、接続を正しく使用している非同期 Bean の一例を示します。
class GoodAsynchBean { DataSource ds; public GoodAsynchBean() throws NamingException { // ok to cache a connection factory or datasource // as class instance data. InitialContext ic = new InitialContext(); // it is assumed that the created J2EE component has this // resource reference defined in its deployment descriptor. ds = (DataSource)ic.lookup("java:comp/env/jdbc/myDataSource"); } // When the asynchronous bean method is called, get a connection, // use it, then close it. void anEventListener() { Connection c = null; try { c = ds.getConnection(); // use the connection now... } finally { if(c != null) c.close(); } } }
以下に、接続の使い方が正しくない非同期 Bean の一例を示します。
class BadAsynchBean { DataSource ds; // Do not do this. You cannot cache connections across asynch method calls. Connection c; public BadAsynchBean() throws NamingException { // ok to cache a connection factory or datasource as // class instance data. InitialContext ic = new InitialContext(); ds = (DataSource)ic.lookup("java:comp/env/jdbc/myDataSource"); // here, you broke the rules... c = ds.getConnection(); } // Now when the asynch method is called, illegally use the cached connection // and you likely see J2C related exceptions at run time. // close it. void someAsynchMethod() { // use the connection now... } }