uot;user";
}
}
//然后,在resources目录下新建一个springmvc.xml,并将上面的ExampleService注册为一个bean
<beans ....>
<bean class="cn.example.springmvc.boke.service.ExampleService"></bean>
</beans>
接下来,我们就得让web容器来为我们创建ioc容器了,具体由谁来创建呢? Servlet有三大核心组件,即Servlet,用于处理请求;Filter,过滤器,用来拦截或修改请求;Listener,监听器,用于监听某个事件。显然,这里使用Listener最合适,那就由Listener来为我们创建ioc容器
<!-- web.xml中 -->
<!-- 当然,具体的Listener实现类代码是不需要由我们来写的,因为Spring早已内置了一个监听器(ContextLoaderListener),就是用于在基于web.xml的配置中来初始化ioc容器 -->
<web-app ....>
<!-- ContextLoaderListener实现了ServletContextListener,而这个ServletContextListener就是用于监听web应用的生命周期的,当web容器启动或终止web应用的时候,会触发ServletContextEvent事件,而该事件就会由ServletContextListener来处理,因此ContextLoaderListener就会在web应用启动的同时创建ioc容器,加载配置文件,具体可详见源码 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 注意:如果未指定配置文件的路径,那么默认会寻找/WEB-INF/applicationContext.xml配置文件,如果这个配置文件找不到,启动时就会报错
基于web.xml的配置所创建的ioc容器是基于xml配置的ioc容器(XmlWebApplicationContext),它会在容器启动的时候读取加载配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</context-param>
<servlet>
<servlet-name>exampleServlet</servlet-name>
<servlet-class>cn.example.springmvc.boke.servlet.ExampleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>exampleServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
现在ioc容器有了,而且被Spring以WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE为key放到了application域中,现在我们可以在任何地方被获取到它,如下所示
@WebServlet("/example")
public class ExampleServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取application域中的ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE属性值,即我们的ioc容器
XmlWebApplicationContext ctx = (XmlWebApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
//或者也可以使用Spring提供的工具类WebApplicationContextUtils来获取ioc容器,如下
//XmlWebApplicationContext ctx = (XmlWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
//使用ioc容器,获取其中的bean
ExampleService exampleService = ctx.getBean(ExampleService.class);
resp.getWriter().write(exampleService.get());
}
}
//最后,重新启动容器,访问 http://localhost:8080/springmvc/example,会发现页面上出现 user 字符串
当然,向上面这样每次都通过get方法获取,很麻烦,我们可以借助Spring提供的工具类,在Servlet初始化的时候对Servlet进行依赖注入,如下
@WebServlet(urlPatterns = "/example")
public class ExampleServlet extends HttpServlet {
//使用@Autowired注解标注需要进行依赖注入的bean
@Autowired
private ExampleService exampleService;
//Servlet初始化方法
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
//获取application域
ServletContext servletContext = config.getServletContext();
//使用Spring提供的自动注入工具类SpringBeanAutowiringSupport,直接进行依