Java – spring switch implementation based on runtime conditions
This is the simplified version I want to implement
For example, suppose I am an interface called color There are many classes that implement this interface, such as red class, blue class, green class, etc
At runtime, I need to select the implementation according to user input One way to achieve this goal is this
@Autowired @Qualifier("Red") private Color redColor; @Autowired @Qualifier("Green") private Color greenColor; private Color getColorImplementation() { if(userInput=="red") { return redColor; } else if(userInput=="green") { return greenColor; } else { return null; } }
But the problem is that every time I add a new implementation, I have to update the code of the selected implementation, which is the whole purpose of the spring control part reversal What is the correct way to do this with a spring?
Solution
You can automatically assemble all the implementations of related interfaces, and then decide to use them according to the properties provided by the interface
@Autowired private List<Color> colors; public void doSomething(String input) { colors.stream().filter(c -> c.getName().contains(input)).findFirst().ifPresent(c -> { // something } }
This is not so magical, more in line with the OO principle Dependency injection was originally designed to connect things rather than dynamically switch at run time