要按方法级别的@Order注解对@Spring Beans进行排序,可以使用以下步骤:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodOrder {
int value();
}
@Service
public class MyService {
@MethodOrder(2)
public void method2() {
// code here
}
@MethodOrder(1)
public void method1() {
// code here
}
}
import org.springframework.core.OrderComparator;
public class MethodOrderComparator extends OrderComparator {
@Override
public int getOrder(Object obj) {
if (obj instanceof Method) {
Method method = (Method) obj;
MethodOrder annotation = method.getAnnotation(MethodOrder.class);
if (annotation != null) {
return annotation.value();
}
}
return super.getOrder(obj);
}
}
@Autowired
private List myServices;
Collections.sort(myServices, new MethodOrderComparator());
现在,当调用myServices时,它们将按照指定的方法级别@MethodOrder注解进行排序。