spring 获取接口实现类 map set list

spring会自动将IndexService 接口实现类 注入到map和set中

 
@Component
public class MyService {
    
    @Autowired
    private IndexService indexService;

    //IndexInterface接口的实现类会注入到indexList
    @Autowired
    private List indexList;

    //IndexInterface接口的实现类会注入到indexMap
    @Autowired
    private Map indexMap;

    //IndexInterface接口的实现类会注入到indexSet
    @Autowired
    private Set indexSet;

  
}


//直接通过spring获取
@Service
public class IndexServiceFactoryImpl implements ExcelImportFactory, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public IndexServiceHandle getByType(IndexServiceEnum typeEnum) {
        Map indexServiceMap = applicationContext.getBeansOfType(IndexService.class);
        IndexServiceHandle indexServiceHandle = indexServiceMap.get(typeEnum.getHandleName());
        AssertUtil.notNull(indexServiceHandle,EXCEL_FILE_IMPLEMENTATION_IS_NULL);
        return indexServiceHandle;
    }

    @Override
    public IndexServiceHandle getByType(Integer type) {
        AssertUtil.notNull(type, ExceptionCode.EXCEL_FILE_TYPE_IS_NULL);
        return getByType(IndexServiceEnum.get(type));
    }

}

参照地址:   Spring注解之@Autowired - 淡墨痕 - 博客园

你可能感兴趣的:(spring,spring,java,spring,boot)