As a simple plug-in mechanism using Spring, it can be realized very easily as described below.
Simple plug-in mechanism realized by DI container https://blog.ik.am/entries/331
Here, the application order of the plug-ins is also considered.
It's very easy to do, just add @Priority
to define the order.
MyPlugin.java
public interface MyPlugin {
String execute();
}
MyPluginService.java
@Service
public class MyPluginService {
@Autowired
List<MyPlugin> plugins;
public List<String> execute() {
return plugins.stream().map(p -> p.execute()).collect(Collectors.toList());
}
}
PluginController.java
@RestController
public class PluginController {
@Autowired
MyPluginService myPluginService;
@GetMapping("plugins")
public List<String> plugins() {
return myPluginService.execute();
}
}
@Component
@Priority(10)
public class Fuga1Plugin implements MyPlugin {
@Override
public String execute() {
return "Fuga1Plugin";
}
}
@Component
@Priority(50)
public class Hoge1Plugin implements MyPlugin {
@Override
public String execute() {
return "Hoge1Plugin";
}
}
@Component
@Priority(100)
public class Fuga2Plugin implements MyPlugin {
@Override
public String execute() {
return "Fuga2Plugin";
}
}
@Component
@Priority(200)
public class Hoge2Plugin implements MyPlugin {
@Override
public String execute() {
return "Hoge2Plugin";
}
}
Execution result
$ curl http://localhost:8080/plugins | jq .
[
"Fuga1Plugin",
"Hoge1Plugin",
"Fuga2Plugin",
"Hoge2Plugin"
]
By the way, from Spring 4.1, @Priority
is recommended instead of @Order
.
Also, if you use @Conditional
, you can write the applicable conditions, but it seems that you will not have much opportunity to use it.
Recommended Posts