I'm new to Guice, and I'm working it in to an application with a large amount of legacy code. It has several classes that look like this:
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'
}
}
It's pretty clear how to use Guice to bind instances that never change, but what about instances that do change (i.e. transactions)? Is there a way for me to use Guice to inject a different instance of Transaction when it changes? Note that the Transaction instance is not one of the well-supported JPA/Hibernate/Spring transactions
The least invasive approach I can think of (avoiding the need to migrate each and every class that uses a transaction at once) would use Guice to inject Transaction only when instantiating objects, and I'd keep the existing application code that updates transactions when necessary. For example, this Provider could be used to inject new objects with the current instance of 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;
}
}
Application logic would look something like this:
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();
}
Are there other ways to update the instance of Transaction that existing classes use without having to migrate each class at once?