代码
首先创建一个接口和两个实现类:
1 2
| public interface ITestService { }
|
1 2 3 4 5 6 7
|
@Component @Order(-100) public class TestServiceImpl implements ITestService { }
|
1 2 3 4 5 6 7 8 9 10 11
| import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component;
@Component @Order(-2) public class Test2ServiceImpl implements ITestService { }
|
测试
下面将这两个实现类实例注入到集合中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles;
import java.util.List; import java.util.Map; import java.util.Set;
@ActiveProfiles("dev") @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class TestInvokeTest {
@Autowired private List<ITestService> iTestServices;
@Autowired private Set<ITestService> testServices;
@Autowired private Map<String, ITestService> testServicesMap;
@Test public void test() { for (ITestService iTestService : iTestServices) { System.out.println(iTestService.getClass().getName()); } for (ITestService iTestService : testServices) { System.out.println(iTestService.getClass().getName()); } testServicesMap.forEach((key, value) -> { System.out.println(key); System.out.println(value.getClass().getName()); }); }
}
|
看到已经将两个实例注入到集合中了。
反复调整 @order 大小,测试发现只有List 才有顺序控制。map 无顺序,set 底层也是map ,故无顺序