IOC 容器启动入口
建立测试环境
1 2 3 4 5 6 7 8 9 10
| public class SpringSourceTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
MyService myService = context.getBean(MyService.class); myService.sayHello(); } }
|
application.xml:
1 2 3 4 5 6 7 8 9
| <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="myService" class="com.example.MyService"/> </beans>
|
MyService.java:
1 2 3 4 5 6
| public class MyService { public void sayHello() { System.out.println("Hello Spring Source!"); } }
|
第一个关键类:ClassPathXmlApplicationContext
入口:
1 2
| ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
|
构造方法里会调用:
跟源码看 refresh()
refresh() 定义在 AbstractApplicationContext
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| @Override public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { prepareRefresh();
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
prepareBeanFactory(beanFactory);
postProcessBeanFactory(beanFactory);
invokeBeanFactoryPostProcessors(beanFactory);
registerBeanPostProcessors(beanFactory);
initMessageSource();
initApplicationEventMulticaster();
onRefresh();
registerListeners();
finishBeanFactoryInitialization(beanFactory);
finishRefresh(); } }
|