views:

694

answers:

2

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?

A: 

Take a look at Assisted Inject. To use it, define a three-line interface:

public interface DataAccessClassFactory {
  DataAccessClass create(Transaction transaction);
}

...and then use a FactoryProvider binding to bind the factory:

bind(DataAccessClassFactory.class).toProvider(
    FactoryProvider.newFactory(DataAccessClassFactory.class, DataAccessClass.class));

Then you can inject a DataAccessClassFactory wherever you need to construct a DataAccessClass. AssistedInject is included in Guice 2, although it requires a separate .jar file.

Jesse Wilson
This looks like it may be helpful, but I'm not following how I can use this to update the binding of Transaction to the instance that represents the currently-open Transaction. In other words: only one instance of Transaction is used at any given time, but that instance is replaced each time a new transaction is started.Is there a more detailed example of using AssistedInject somewhere? On the wiki page, I'm having trouble figuring out where instances of Date and Money are instantiated.
Kyle Krull
+3  A: 

If I understand this correctly, your problem has two independent parts:

  1. using the right Transaction instance on Guice-fied classes
  2. using the right Transaction instance on legacy classes.

For '1', your custom provider works, but I would create a custom scope for a transaction and bind the Transaction class at that scope. See http://code.google.com/p/google-guice/wiki/CustomScopes for instructions about custom scopes.

Regarding '2', once you have a custom scope, this is the usual problem of using Guice to provide instances to legacy classes. You didn't mention the code that currently provides Transaction instances to legacy classes, but you could just change that particular piece of code to request an instance from Guice. Since you are inside your "transaction scope", Guice takes care of providing the right instance.

Fernando
Thanks - this looks like it would work. Good point on refactoring the legacy classes to request Transactions from Guice - it looks like it would only be a small change to each legacy class, and it would probably be a lot easier than using 2 systems for managing transactions.
Kyle Krull