<!-- servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- servlet-jsp-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
<!-- spring-context-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!-- jdbc-druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<!-- jdbc-c3p0-->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- spring-web-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
public class ApplicationContextLoaderUtil {
public static ApplicationContext getApplicationContext(ServletContext servletContext){
//在域中获取applicationContext对象
ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app");
//测试
System.out.println("通过工具类获取app");
return app;
}
}
手动配置(web.xml中)
<!-- 全局初始化参数-->
<!--applicationContext文件名-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
内部封装好
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//在servletContext中获取ApplicationContext对象
//获取servletContext
ServletContext servletContext = request.getServletContext();
//获取app对象(使用工具包中的方法)
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
//获取userService
UserService userService = app.getBean(UserService.class);
userService.save();
配置pom.xml时:
servlet-api和servlet-jsp-api时应该加入范围
<scope>provided</scope>
applicationContext.xml中:
添加扫描注解
<context:component-scan base-package="dao"/>
<context:component-scan base-package="service"/>
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/115198.html原文链接:https://javaforall.cn