Spring在代码中获取bean的方式(获取接口所有实现类)

方法一:在初始化时保存ApplicationContext对象
方法二:通过Spring提供的utils类获取ApplicationContext对象
方法三:继承自抽象类ApplicationObjectSupport
方法四:继承自抽象类WebApplicationObjectSupport
方法五:实现接口ApplicationContextAware
方法六:通过Spring提供的ContextLoader

方法一:在初始化时保存ApplicationContext对象

@Service
public class ApplicationContextLoader {

    /**
     * 用于保存接口实现类名及对应的类
     */
    private Map<String, IService> map;

    @Autowired
    ApplicationContext applicationContext;

    @PostConstruct
    public void init(){
        //根据接口类型返回相应的所有bean
        Map<String, IService> map = applicationContext.getBeansOfType(IService.class);
        System.out.println(map);
    }

    public Map<String, IService> getMap() {
        return map;
    }

}

参考范例博客地址:https://www.cnblogs.com/yjbjingcha/p/6752265.html

原文地址:https://www.cnblogs.com/jelly12345/p/14799917.html