ContextLoader.properties内容简介说明
下文笔者讲述ContextLoader.properties简介说明,如下所示
ContextLoader.properties文件简介
`ContextLoader.properties`文件不是Spring框架中默认提供的配置文件 此文件是Springweb中使用的配置,如何定义默认的 WebApplicationContext 接口的实现类 ContextLoader.properties文件在 ContextLoaderlistener 中静态代码里加载
自定义 ContextLoader.properties文件
1.`web.xml`中的配置
<web-app>
<!-- 配置 ContextLoaderListener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 指定 Spring 配置文件的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<!-- 可选:指定自定义上下文类 -->
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
</web-app>
2.Java 配置类
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class MyWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
// 创建根上下文
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(RootConfig.class);
servletContext.addListener(new ContextLoaderListener(rootContext));
// 创建 DispatcherServlet 上下文
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.register(WebConfig.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
自定义`ContextLoader.properties`
# ContextLoader.properties 示例 # 指定上下文配置文件位置 contextConfigLocation=/WEB-INF/applicationContext.xml # 指定自定义上下文类 contextClass=org.springframework.web.context.support.AnnotationConfigWebApplicationContext # 其他自定义参数 customParameter1=value1 customParameter2=value2
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


