Search code examples
javaapache-camelosgijbossfuseblueprint-osgi

How to use an OSGI reference from another bundle in java


Im working with JBoss Fuse, I have created a bundle that exports a DataSouce and now I want to query it.

There's a reference to said DataSource in the blueprint of another bundle:

  <reference 
      id="myDataSource"
      filter="(osgi.jndi.service.name=myDataSouce)" 
      interface="javax.sql.DataSource"
  />

How can I access this reference from java code so I can query it?


Solution

  • You can create a custom Bean:

    <bean id="myDsBean" class="my.company.MyDsBean">
        <property name="dataSource" ref="myDataSource" />
    </bean>
    

    Java code:

    public class MyDsBean {
    
        private JdbcTemplate myds;
    
        public void setDataSource(DataSource ds) {
            this.myds = new JdbcTemplate(ds);
        }
        // Code to query data source
    }
    

    My example is using JdbcTemplate but you can substitute that to whatever you want to use.