On Tue, 2020-12-15 at 14:35 +0100, Nicola Cisternino wrote:
> Hi Robert.
> Declarative services are best way ... but i need to use different 
> datasources starting from a (request) payload attribute received from
> a 
> servlet ...
> So I decided to migrate (in a bundle service)  the custom pool engine
> that we used in the old webapp.

I would suggest trying the following (may need adjustment, typing out
of memory):

private Map<String, DataSource> dataSources = new
ConcurrentHashMap<>();

private BundleContext ctx;

@Activate
void activate(BundleContext ctx) {
  this.ctx = ctx;
}

@Reference(service=DataSource.class, policy = DYNAMIC,
cardinality=MULTIPLE)
void bindDataSource(ServiceReference<DataSource> ref) {
  dataSources.put((String) ref.getProperty("datasource.name"),
ctx.getServiceReference(ref));
}

void unbindDataSource(ServiceReference<DataSource> ref) {
  dataSources.remove((String) ref.getProperty("datasource.name"));
}

This way you get the datasources injected and via SCR and you get to
use the datasource.name as a key. There is probably more defensive
coding needed, but this is what I would use as a starting point.

Thanks,
Robert

> 
> Thanks.
> Nicola.
> 
> Il 12/14/20 12:55 PM, Robert Munteanu ha scritto:
> > Hi Nicola,
> > 
> > On Fri, 2020-12-11 at 16:16 +0100, Nicola Cisternino wrote:
> > > Hi all
> > > 
> > > I'm using Sling Datasource Bundle (org.apache.sling.datasource)
> > > and I
> > > configured two entries named (datasource.name property):
> > > *source1*
> > > and
> > > *source2*.
> > > I can select single datasource using DS annotations:
> > > 
> > > @Reference(target =
> > > "(&(objectclass=javax.sql.DataSource)(datasource.name=*source1*))
> > > ")
> > > private DataSource dataSource;
> > > 
> > > But ... how can I select single datasource programmatically ?
> > How do you select the datasources programatically now?
> > 
> > As a side note, I'd try to stick to declarative services as much as
> > possible as it makes things simpler to write and understand.
> > 
> > Thanks,
> > Robert
> > 
> 


Reply via email to