使用spring核心监听器ContextLoaderListener
引入jar包 spring-web.jar
配置监听器:
<!-- Spring的核心监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 加载Spring的配置文件的路径的,默认加载的/WEB-INF/applicationContext.xml -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
直接在Action当中获取工厂
@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.service(req, resp);
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
// 获取工厂 程序启动时,保存到ServletContext中
ServletContext servletContext = this.getServletContext();
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
// 获取对象
UserService userService = (UserService)applicationContext.getBean("userService");
userService.save();
}
}
public class UserService {
public void save(){
System.out.println("-save-");
}
}
applicationContext.xml 中配置:
<bean id="userService" class="com.study.ssh.demo2.UserService"/>
原文:https://www.cnblogs.com/xzh0717/p/10946644.html