1、指定限定名注入實(shí)現(xiàn)類
1.1、定義一個(gè)接口
public interface AnimalService {
1.2、創(chuàng)建多個(gè)實(shí)現(xiàn)類
public class CatService implements AnimalService { System.out.println("喵喵喵");
public class DogService implements AnimalService { System.out.println("汪汪汪");
public class CattleService implements AnimalService { System.out.println("汪汪汪");
1.3、指定限定名注入實(shí)現(xiàn)類
@RunWith(SpringRunner.class) AnimalService animalService1; //正常啟動(dòng) //沒有指定bean注入名字的,使用該類首字符小寫的bean的名字 @Resource(name = "dogService") AnimalService animalService2; //正常啟動(dòng) //通過@Resource注入,根據(jù)@Service指定的名稱區(qū)分 AnimalService animalService3; //正常啟動(dòng)
2、Map名注入實(shí)現(xiàn)類
2.1、定義一個(gè)接口
public interface AnimalService {
2.2、創(chuàng)建多個(gè)實(shí)現(xiàn)類
public class CatService implements AnimalService { System.out.println("喵喵喵");
public class DogService implements AnimalService { System.out.println("汪汪汪");
2.3、枚舉
public enum AnimalTypeEnum { DOG(1, "狗狗", "dogService"), CAT(2, "貓咪", "catService"); public static AnimalTypeEnum getAnimalTypeEnum (Integer code) { return (AnimalTypeEnum )Arrays.stream(values()).filter((item) -> { return item.code.equals(code); }).findFirst().orElseThrow(() -> { return new BusinessException("biz animal type is not exist"); private AnimalTypeEnum (final Integer code, final String msg, final String service) {
2.4、指定限定名注入實(shí)現(xiàn)類
@RunWith(SpringRunner.class) Map<String, AnimalService> animalServiceMap; String service = AnimalTypeEnum.getAnimalTypeEnum(1).service; AnimalService animalService = animalServiceMap.get(service);
|