Child pages
  • Extending an Application with Custom Plugins

Versions Compared

Key

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

In this tutorial, we will show how easily your our application can be made extensible using the Struts 2 plugins plugin mechanism. To keep the demonstration simple, our plugin will expose a JavaBean that writes a message. Your plugins can Plugins may include any combination of JavaBeans, Actions, Interceptors, Results or whatever other resources youwe'd like available to pluginan application.

The Interface

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

...

Now that we have an interface to implement , lets create an actual we'll create the plugin. At load time, the framework looks for JARs with contain containing a struts-plugin.xml file at the root of the archive. To create a plugin, all we need to do is build a JAR and put the expected struts-plugin.xml at the root.

...

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

import example.IMyPlugin; 

public class MyPlugin implements IMyPlugin {
   public String saySomething() {
       return "We don't need no education";
//Sorry, I couldn't help it :)
   }
}

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.

...

Finally, to install the plugin, just drop the JAR file under WEB-INF/lib.

...

The JavaBeans configured by the bean element elements can be retrieved via a Container provided by XWork 2. We can obtain a reference to the Container by using the @Inject notation. (This notation is part of the Guice framework that XWork and Struts use under the covers.) The framework predefines a Container object, and the @Inject notion annotation tells the framework to set its Container object to the Action property.

...

Code Block
Java
Java
titleMyAction.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;
    }
}

...