I have two java packages - package-A, package-B Let us say this is the dependency chains of the packages.
package-A -> package-B
I want to pass custom Java function that would be executed in package-A. How do I do that?
package-A
- src
- Foo.java
package-B
- src
- Bar.java
- Tag.java
class Foo implements Tag {
doThis() {
// do what I say.
}
}
------------------------------------------
class Bar {
execute() {
tag.doThis();
}
}
interface Tag {
doThis();
}
I want some sort of plugin framework, so that package-A owners can provide an implementation to all users of library package-B without package-B having to depend on package-A
OSGi has a service registry. A plugin (a bundle) can register a service object under its interface name. Other plugins can get that service. For example, in
Tag.javawe have:The provider of the service can provide an implementation as follows:
The
@Componentannotation is defined by OSGi. When the program starts, it will register aTagservice.The next part is the consumer in
Bar.java:The
@Componentwill create an instance ofBarand will pass an instance of theTagservice to the constructor because it has a@Activateand@Referenceannotation.As a tip, you want to package the consumer, the interface, and the provider in three different bundles.
A simple example of this pattern is shown in a bndtools video