您可以编写包装类,它有一些顺序字段,您可以使用这些字段对计算器进行排序,或者简单地将该字段添加到bean中,或者添加更多接口…选项由您选择。
在这个简单的排序计算器之后,按您的“order”字段使用foreach。
下面评论中提出的例子。(这完全不是生产就绪代码,只是为了给您举个例子)
package org.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.util.Comparator;
import java.util.List;
@Configuration
@ComponentScan
public class Main {
@Autowired
List<Calculator> calculators;
public void start() {
calculators.stream().sorted(Comparator.comparing(Calculator::getOrder)).forEach(Calculator::calculate);
}
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(Main.class);
ctx.refresh();
Main main = ctx.getBean(Main.class);
main.start();
}
}
interface Calculator {
void calculate();
int getOrder();
}
@Component
class FirstCalc implements Calculator {
@Override
public void calculate() {
System.out.println(String.format("firstCalc with order %s", getOrder()));
}
@Override
public int getOrder() {
return 1;
}
}
@Component
class SecondCalc implements Calculator {
@Override
public void calculate() {
System.out.println(String.format("secondCalc with order %s", getOrder()));
}
@Override
public int getOrder() {
return 1;
}
}
@Component
class ThirdCalc implements Calculator {
@Override
public void calculate() {
System.out.println(String.format("thirdCalc with order %s should be 3rd", getOrder()));
}
@Override
public int getOrder() {
return 2;
}
}
@Component
class FourthCalc implements Calculator {
@Override
public void calculate() {
System.out.println(String.format("lastCalc with order %s should be last", getOrder()));
}
@Override
public int getOrder() {
return 3;
}
}
结果将是:
firstCalc with order 1
secondCalc with order 1
thirdCalc with order 2 should be 3rd
lastCalc with order 3 should be last