public abstract class CargoFilter implements Comparable<CargoFilter> {
abstract boolean shouldFilter(Cargo cargo);
abstract int filterOrder();
@Override
public int compareTo(CargoFilter cargoFilter) {
return Integer.compare(this.filterOrder(), cargoFilter.filterOrder());
}
}
@Service
public class CargoIdFilter extends CargoFilter {
@Override
public boolean shouldFilter(Cargo cargo) {
if (cargo.getCargoId() > 0) {
System.out.println("CargoIdFilter run");
return true;
}
return false;
}
@Override
public int filterOrder() {
return 1;
}
}
@Service
public class CargoNameFilter extends CargoFilter {
@Override
public boolean shouldFilter(Cargo cargo) {
if (Objects.nonNull(cargo.getName())) {
System.out.println("CargoNameFilter run");
return true;
}
return false;
}
@Override
public int filterOrder() {
return 2;
}
}
@Service
public class CargoCategoryFilter extends CargoFilter {
@Override
public boolean shouldFilter(Cargo cargo) {
if ("toys".equals(cargo.getCategory())) {
return true;
}
System.out.println("CargoCategoryFilter run");
return false;
}
@Override
public int filterOrder() {
return 3;
}
}
@Data
@AllArgsConstructor
@ToString
public class Cargo {
private Long cargoId;
private String name;
private String category;
}
@Component
public class ServiceLocator {
@Autowired
private ApplicationContext context;
public List<CargoFilter> getCargoFilterList() {
List<CargoFilter> cargoFilterList = new ArrayList<>();
Map<String, CargoFilter> cargoFilterMap = context.getBeansOfType(CargoFilter.class);
for (String key : cargoFilterMap.keySet()) {
cargoFilterList.add(cargoFilterMap.get(key));
}
Collections.sort(cargoFilterList);
return cargoFilterList;
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
class SpringBootDemoApplicationTests {
@Autowired
private ServiceLocator serviceLocator;
@Test
void contextLoads() {
}
@Test
void test(){
Cargo cargo = new Cargo(10000l, "apple", "fruit");
List<CargoFilter> cargoFilterList = serviceLocator.getCargoFilterList();
cargoFilterList.forEach(cargoFilter -> cargoFilter.shouldFilter(cargo));
}
}
CargoCategoryFilter run
CargoNameFilter run
CargoIdFilter run