...
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 |
---|
| Java | Java |
---|
title | IMyPlugin.java |
---|
| Java |
---|
|
package example;
public interface IMyPlugIn {
String saySomething();
}
|
...
To get started, let's create a class that implements our IMyPlugin interface.
Code Block |
Java |
---|
| Java |
---|
title | MyPlugin.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.
Code Block |
XML |
---|
| XML |
---|
title | struts-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 |
---|
| Java | Java |
---|
title | MyAction.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 |
---|
|
<s:iterator id="plugin" value="plugins">
<s:property value="#plugin.saySomething()"/>
</s:iterator>
|