1. 程式人生 > >springboot 將實現同一介面的Service注入到Map當中 方法五

springboot 將實現同一介面的Service注入到Map當中 方法五

同一介面

public interface SayService {

    public String hello();
}

介面的不同實現

@Service("sayOne")
public class SayServiceOne implements SayService {
    @Override
    public String hello() {
        System.out.println("say one");
        return "say one";
    }
}
@Service("sayTwo")
public class SayServiceTwo implements SayService {
    @Override
    public String hello() {
        System.out.println("say two");
        return "say two";
    }
}

裝載到map,作為bean注入到spring中


@Component
public class MapConfig {


     @Bean(name="actServiceMap")
    public Map<String, SayService> getQueryServiceMap(){
        return  new HashMap<>();
        
    }
}

或者自定義key

@Component
public class MapConfig {

    @Resource(name = "sayOne")
    private SayService sayOne;

    @Autowired
    @Qualifier("sayTwo")
    private SayService sayTwo;

    @Bean("sayServiceMap")
    public Map<String, SayService> geneSayServiceMap(){
        Map<String, SayService> sayServiceMap = new HashMap<>();
        sayServiceMap.put("sayOne自定義", sayOne);
        sayServiceMap.put("sayTwo自定義", sayTwo);
        return sayServiceMap;
    }
}

或者這樣寫也可

@Component
public class ActMap {

    @Bean(name="actServiceMap")
    public Map<String, ActService> geneActServiceMap(@Qualifier("actOne") ActService actOne,
                                                     @Qualifier("actTwo") ActService actTwo){
        Map<String, ActService> map = new HashMap<>();
        map.put("actOne111", actOne);
        map.put("actTwo2222", actTwo);
        return map;
    }
}

測試

@RestController
@RequestMapping("/beanTest")
public class BeanTest {

    @Resource(name="sayServiceMap")
    Map<String, SayService> sayServiceMap;

    @GetMapping("/say")
    public String say(){
        SayService sayOne = sayServiceMap.get("sayOne");
        SayService sayTwo = sayServiceMap.get("sayTwo");

        return sayOne.hello() + "\n" + sayTwo.hello();
    }
}