@Order注解提供消费顺序
Order注解可以做到集合bean依赖注入的时候,定义集合内部Bean的加载顺序,因此在需要有序消费bean的时候,不需要再次排序,直接定义好Order注解得value值就好。
但是这个order值并不影响bean本身实例化的顺序,因为实例化的顺序取决于依赖关系。
@org.springframework.core.annotation.Order
@RestController
@RequestMapping(value = "/pc/api/v1/monitor")
@RequiredArgsConstructor
public class AfterRepairConsumer {
private final List<RepairCreatePostConsumer> postConsumers;
@GetMapping(value = "/create")
public ResponseData create() {
final String repairId = "1";
if (CollectionUtils.isNotEmpty(postConsumers)) {
postConsumers.forEach(e -> e.postHandler(repairId));
}
return new ResponseData<>("success");
}
}
public interface RepairCreatePostConsumer {
/**
* 创建报修单后做什么
*
* @param repairId 报修单ID
*/
void postHandler(String repairId);
}
import org.springframework.core.annotation.Order;
@Service
@RequiredArgsConstructor
@Order(value = 3)
public class SendEmail implements RepairCreatePostConsumer {
@Override
public void postHandler(String repairId) {
System.out.println("为报修单" + repairId + "发送邮件");
}
}
import org.springframework.core.annotation.Order;
@Service
@RequiredArgsConstructor
@Order(value = 2)
public class SendInvoice implements RepairCreatePostConsumer {
@Override
public void postHandler(String repairId) {
System.out.println("为报修单" + repairId + "发送发票");
}
}
import org.springframework.core.annotation.Order;
@Service
@RequiredArgsConstructor
@Order(value = 1)
public class SendMessage implements RepairCreatePostConsumer {
@Override
public void postHandler(String repairId) {
System.out.println("为报修单" + repairId + "发送消息");
}
}
运行结果: