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?
source
share