Tuesday, October 30, 2007

OSGi – Spring Quartz job

Mark’s blog provides a good example of how to provide the Spring application context to a Job. Here I will show how to ’inject’ OSGi services into your Spring OSGi application. This will become much cleaner once Spring Dynamic Modules executor bundle is released but at the moment using Spring 2.0.7 I need to provide some OSGi services to my Quartz job.
I have say a bundle ‘MyServiceBundle’ that registers a service with the following interface:
package com.irahul.example.myservicebundle; 
public interface TransactionService{ 
    void updateTransaction(Long id, String status); 
}
The activator looks something like:
package com.irahul.example.myservicebundle; 
public class Activator implements BundleActivator { 
    public void start(BundleContext bundleContext){ 
       TransactionService txnSvc = new ....//an implementation of it 
       Map<String,String> metaProperties = new... 
       //define whatever meta data you want to register for service discovery 
       bundleContext.registerService("com.irahul.example.TransactionService", 
          txnSvc,metaProperties); 
    } 
}
Now over in the bundle ‘MyQuartzJob’ define a JobContext which can be injected with all the beans it requires to perform the Job.
package com.irahul.example.myquartzjob; 
public interface JobContext{ 
    void setTransactionService(TransactionService txnSvc); 
    TransactionService getTransactionService(); 
}
Implement the QuartzJobBean to get the application context like in Mark’s blog. Now in your application context create an empty bean with your JobContext implementation.
<!-- Job Context --> 
<bean id="jobContext" class="com.irahul.example.myquartzjob.JobContextImpl"></bean>
After that all that remains is the activator, which looks like:
package com.irahul.example.myquartzjob
public class Activator implements BundleActivator { 
    public void start(BundleContext bundleContext){ 
    // Initialize the Spring application context 
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext( 
         new String[]{"context.xml"}); 
    //get the service 
    ServiceReference txnRef = bundleContext. 
               getServiceReference("com.irahul.example.TransactionService"); 
               //you can search on additonal meta data filter as well 
    TransactionService txnService = (TransactionService)bundleContext.getService(txnRef); 
    //now get the spring bean as setup 
    JobContext jobContext = (JobContext)applicationContext.getBean("jobContext"); 
    jobContext.setTransactionService(txnService); 
}
Your Job now has the application context all setup and ready to go!

No comments: