私は Guice を初めて使用し、大量のレガシー コードを含むアプリケーションで Guice を使用しています。次のようないくつかのクラスがあります。
public final class DataAccessClass {
private Transaction txn;
@Inject //This was just added
public DataAccessClass(/* injectable parameters */, Transaction txn) {
this.txn = txn;
}
//Maybe add @Inject here to set a new transaction when it changes?
public void setTransaction(Transaction txn) {
this.txn = txn;
}
public void writeData(/* parameters for data to be written */) {
//Write data using the current instance of 'txn'
}
}
Guice を使用して変更されないインスタンスをバインドする方法は明らかですが、変更されるインスタンス (つまりトランザクション) はどうなるでしょうか? Guice を使用して、Transaction が変更されたときに別のインスタンスを挿入する方法はありますか? Transaction インスタンスは、十分にサポートされている JPA/Hibernate/Spring トランザクションの 1 つではないことに注意してください。
私が考えることができる最も侵襲性の低いアプローチ (トランザクションを使用するすべてのクラスを一度に移行する必要を回避する) は、Guice を使用して、オブジェクトをインスタンス化するときにのみ Transaction を注入し、必要に応じてトランザクションを更新する既存のアプリケーション コードを保持します。 . たとえば、このプロバイダを使用して、トランザクションの現在のインスタンスで新しいオブジェクトを挿入できます。
public final class TransactionProvider implements Provider<Transaction> {
/** Nullable transaction that should be used for all operations at the moment */
private Transaction txn;
public TransactionProvider(Transaction txn) {
this.txn = txn;
}
/**
* @param txn Nullable transaction to use for all operations at the moment
*/
public void setTransaction(Transaction txn) {
this.txn = txn;
}
/* Provider methods */
public Transaction get() {
return this.txn;
}
}
アプリケーション ロジックは次のようになります。
public final class Application {
private final Provider<Transaction> transactionProvider;
private final DataAccessClass dao; //Instance provided by Guice
public void scopedOperation() {
//Use a fresh transaction for this operation
final Transaction txn = ...;
//Make transaction available to Guice (for new objects) and to legacy (already-instantiated) DAO classes
this.transactionProvider.setTransaction(txn);
this.dao.setTransaction(txn); //Legacy approach - can this be updated?
//Do some kind of data operation under the scope of the current transaction
try {
this.dao.writeData(...);
} catch (Exception e) {
txn.abort();
throw new RuntimeException("Operation failed", e);
}
//The operation is over now
this.txn.commit();
}
各クラスを一度に移行することなく、既存のクラスが使用する Transaction のインスタンスを更新する他の方法はありますか?