目录
- 1、指定限定名注入实现类
- 1.1、定义一个接口
- 1IWzMDqzCB.2、创建多个实现类
- 1.3、指定限定名注入实现类
- 2、Map名注入实现类
- 2.1、定义一个接口
- 2.IWzMDqzCB2、创建多个实现类
- 2.3、枚举
- 2.4、指定限定名注入实现类
1、指定限定名注入实现类
1.1、定义一个接口
public interface AnimalService { public void sound(); }
1.2、创建多个实现类
@Service("s1") public class CatService implements AnimalService { @Override public void sound() { System.out.println("喵喵喵"); } }
@Service() public class DogService implements AnimalService { @Override public void sound() { System.out.println("汪汪汪"); } }
@Service("s3") public class CattleService implements AnimalService { @Override public void sound() { System.out.println("汪汪汪"); } }
1.3、指定限定名注入实现类
@RunWith(SpringRunner.class) @SpringBootTest public class Main { @Autowired @Qualifier(value = "s1") AnimalService animalService1; //正常启动 //没有指定bean注入名字的,使用该类首字符小写的bean的名字 //使用默认的 @Resource(name = "dogService") AnimalService animalService2; //正常启动 //通过@Resource注入,根据@Service指定的名称区分 @Resource(name = "s3") AnimalService animalService3; //正常启动 @Test public void test1() { animalService1.sound(); animalService2.sound(); animalService3.sound(); } }
2、Map名注入实现类
2.1、定义一个接口
public int编程客栈erface AnimalService { public void sound(); }
2.2、创建多个实现类
@Service("s1") public class CatService implements AnimalService { @Override public void sound() {javascript System.out.prpythonintln("喵喵喵"); } }
2.3、枚举
public enum AnimalTypeEnum { DOG(1, "狗狗", "dogService"), CAT(2, "猫咪", "catService"); public Integer code; public String msg; public String service; 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) { this.code = code; this.msg = msg; this.service = service; } }
2.4、指定限定名注入实现类
@RunWith(SpringRunner.class) @SpringBootTest public class Main { @Autowired Map<String, AnimalService> animalServiceMap; @Test public void test1() { String service = AnimalTypeEnum.getAnimalTypeEnum(1).service; AnimalService animalService = animalServiceMap.get(service); animalService.sound(); } }
以上就是SpringBoot一个接口多个实现类的调用方式的详细内容,更多关于SpringBoot一个接口多个实现类的资料请关注编程客栈(www.devze.com)其它相关文章!
精彩评论