spring容器初始化分为大概分为两种方式:通过tomcat容器启动Spring (适用于web环境)和java常规启动
web.xml配置
<!-- 从类路径下加载Spring配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param>
<!-- 负责启动Spring容器的监听器,它将应用上面的配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Spring 启动过程大致分为两个过程:1、ContextLoaderListener初始化,实例化IoC容器,2并将此容器实例注册到ServletContext中
ContextLoader 类的静态代码块,通过配置文件的方式加载WebApplicationContext的具体实现
static {
// Load default strategy implementations from properties file.
// This is currently strictly internal and not meant to be customized
// by application developers.
try {
ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
}
catch (IOException ex) {
throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());
}
}
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}