spring中集合的注入(list,map等)


前言

这种用法是在看别人代码的时候学到的,觉得挺有意思的,记录一下。

具体用法

首先新建一个接口

public interface PlService {
}

新建两个这个接口的实现类

@Service
public class AService implements PlService {
    public AService() {
        System.out.println("----------------------- AService 实例化 ------------------------");
    }
}

@Service
public class BService implements PlService {

    public BService() {
        System.out.println("------------------------------- BServive 实例化 ------------------------");
    }
}

在另一个类中注入集合

我是在一个启动的runner中注入的:

@Component
@Slf4j
public class PlEurekaServerRunner implements ApplicationRunner {

    @Autowired
    private List<PlService> services;

    @Autowired
    private Map<String, PlService> serviceMap;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        for (PlService service : services) {
            log.info("++++++++++++++++++++ {}+++++++++++++++++++ ", service.getClass().getName());
        }

        for (Map.Entry<String, PlService> entry : serviceMap.entrySet()) {
            log.info("======================= {} : {} ====================", entry.getKey(), entry.getValue());
        }
    }

}

注入的结果

如果是List的话,会注入该接口的所有实现类;如果是Map的话,key为类名,value为实现类。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM