Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

...

At runtime, plugins are retrieved and referenced via an Interface. So, first, we should define an interface that our plugin will implement. This interface must be available to both our web application and the plugin. To reduce coupling between the web application and the plugins, keep the interface in a separate JAR.

Code Block
JavaJava
titleIMyPlugin.java
Java
package example;

public interface IMyPlugIn {
   String saySomething();
}

...

To get started, let's create a class that implements our IMyPlugin interface.

Java
Code Block
Java
titleMyPlugin.java
Java
package example.impl;

import example.IMyPlugin; 

public class MyPlugin implements IMyPlugin {
   public String saySomething() {
       return "We don't need no education";
   }
}

Internally, the framework utilizes a number of JavaBeans. We can use the bean element to add our own JavaBeans to the set managed by the framework.

XML
Code Block
XML
titlestruts-default.xml
XML
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <bean type="example.IMyInterface" class="example.impl.MyPlugin" name="myPlugin"/>
</struts>

...

We might want to supply a number of JavaBeans to the application this way. In the Action, we will obtain a reference to the entire set of JavaBeans that might have been plugged in. Then, we can scroll through the set, displaying each JavaBean's message.

Code Block
JavaJava
titleMyAction.java
Java
package example.actions;

import example.IMyPlugin;

public class MyAction extends ActionSupport {
    Set<IMyPlugin> plugins;

    @Inject
    public void setContainer(Container container) {
        Set<String> names = container.getInstanceNames(IMyPlugin.class);
        plugins = new HashSet<IMyPlugin>();
        for (String name : names) {
            plugins.add(container.getInstance(IMyPlugin.class, name));
        }
    }

    public Set<IMyPlugin> getPlugins() {
        return this.plugins;
    }
}

...

Let's do something with those plugins:

Code Block
xmlxml
titlePage.jsp
xml
<s:iterator id="plugin" value="plugins">
  <s:property value="#plugin.saySomething()"/>
</s:iterator>