我们经常会看到 如下代码
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(configPath.split("[,\s]+")); context.start();
其实该context.start()的作用就是初始话配置文件中的bean对象
//--------------------------------------------------------------------- // Implementation of Lifecycle interface //--------------------------------------------------------------------- public void start() { Map lifecycleBeans = getLifecycleBeans(); for (Iterator it = new LinkedHashSet(lifecycleBeans.keySet()).iterator(); it.hasNext();) { String beanName = (String) it.next(); doStart(lifecycleBeans, beanName); } publishEvent(new ContextStartedEvent(this)); } /** * Start the specified bean as part of the given set of Lifecycle beans, * making sure that any beans that it depends on are started first. * @param lifecycleBeans Map with bean name as key and Lifecycle instance as value * @param beanName the name of the bean to start */ private void doStart(Map lifecycleBeans, String beanName) { Lifecycle bean = (Lifecycle) lifecycleBeans.get(beanName); if (bean != null) { String[] dependenciesForBean = getBeanFactory().getDependenciesForBean(beanName); //找到依赖的类 for (int i = 0; i < dependenciesForBean.length; i++) { doStart(lifecycleBeans, dependenciesForBean[i]);//递归调用找到依赖的类 } if (!bean.isRunning()) { bean.start(); } lifecycleBeans.remove(beanName); } }