Multiple instances of the same provider

I created a DataSourceProvider to search for a container-controlled dataSource:

public class ContainerDataSourceProvider implements Provider<DataSource> {
    private final DataSource ds;

    @Inject
    ContainerDataSourceProvider (String dataSourceName) throws NamingException {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        ds = (DataSource) envCtx.lookup("jdbc/" + dataSourceName);
    }

    @Override
    public DataSource get() {
        return ds;
    }
}

I cannot use the @Named annotation for the provider, since I want to be able to provide different data sources depending on dataSourceName.

In my module, I want to provide several dataSource bindings using a provider. The name jdni datasorce comes from a properties file already bound to names.

//How do I configure ContainerDataSourceProvider with jndi name "userDataSource"????
binder.bind(DataSource.class).annotatedWith(UserDS.class)
                .toProvider(ContainerDataSourceProvider.class);

//How do I configure ContainerDataSourceProvider with jndi name "sessionDataSource"????
binder.bind(DataSource.class).annotatedWith(SessionDS.class)
                .toProvider(ContainerDataSourceProvider.class);

Then in my code I can do something like

public class UserDSClient {
       @Inject UserDSClient (@UserDS DataSource ds) {}
}

public class SessionDSClient {
       @Inject SessionDSClient (@SessionDS DataSource ds) {}
}

How can i achieve this?

+1
source share
2 answers

It is pretty simple. Create the provider manually by passing the name of the data source to its constructor:

public class ContainerDataSourceProvider implements Provider<DataSource> {
    private final String dataSourceName;

    @Inject
    ContainerDataSourceProvider (String dataSourceName) {
        this.dataSourceName = dataSourceName;
    }

    @Override
    public DataSource get() {
        try {
            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            return (DataSource) envCtx.lookup("jdbc/" + dataSourceName);
        } catch (NamingException e) {
            throw new RuntimeException(e);
        }
    }
}

get(). , - Guice , . :

binder.bind(DataSource.class).annotatedWith(UserDS.class)
    .toProvider(new ContainerDataSourceProvider("userDataSource"))
    .in(Singleton.class);

binder.bind(DataSource.class).annotatedWith(SessionDS.class)
    .toProvider(new ContainerDataSourceProvider("sessionDataSource"))
    .in(Singleton.class);

.

BTW, - , ( Guice.createInjector(), injector.getInstance()), , , . , .

+1

. . , Annotations.

, . , . http://slid.es/milanbaran/dec

0

All Articles