Expand my Community achievements bar.

Learn about Edge Delivery Services in upcoming GEM session

Run Java Class on Bundle Start

Avatar

Level 2

Hi,

Is there a way to run a java class on a bundle start up like a main class?

2 Replies

Avatar

Level 2

You can put an OSGi service component inside the bundle and in activate method of the service component you can run your java class.

e.g.

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;

@Component

@Service

public class MyApplicationStarterService{

  @Activate
  protected void activate(ComponentContext ctx) {

      MyAppClass app = new MyAppClass();

      app.run();

  }

}

Avatar

Employee Advisor

This isn't exactly answering the question, because the activation of this component is lazy, and thus is asynchronous to the activation of a bundle.

Instead you should specify a BundleActivator in the metadata of your OSGI bundle. The code of this class is executed during the bundle start (also meaning, that an unhandled exception in the BundleActivator prevents the bundle from starting.

The definition in the POM: acs-aem-commons/pom.xml at master · Adobe-Consulting-Services/acs-aem-commons · GitHub

The BundleActivator class: acs-aem-commons/Activator.java at master · Adobe-Consulting-Services/acs-aem-commons · GitHub

regards,

Jörg