[JAVA] Simple plugin mechanism in Spring, also consider the order

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

Simple plugin mechanism in Spring, also consider the order
Install the plugin in Eclipse
Use the Findbugs plugin in Eclipse
Spring validation was important in the order of Form and BindingResult
Order of processing in the program
Spring Autowired is written in the constructor
Console input in Java (understanding the mechanism)
[Order method] Set the order of data in Rails
View the Gradle task in the Spring Boot project