servlet中使用spring

简单介绍一下了 呵呵 
在我们的项目中,可能需要单独使用servlet,而这个servlet又需要去获取spring的配置信息,来获得数据库中的数据。 

Java代码   收藏代码
  1. public void doPost(HttpServletRequest request, HttpServletResponse response)  
  2.             throws ServletException, IOException {  
  3.         ServletContext application;  
  4.         WebApplicationContext wac;  
  5.         application = getServletContext();  
  6.         wac = WebApplicationContextUtils.getWebApplicationContext(application);//获取spring的context  
  7. UserInfoDAOImpl user = (UserInfoDAOImpl) wac.getBean("userInfoDAO");  
  8.                 PrintWriter out = response.getWriter();  
  9.                 out.print(user.getAllUser().size());  
  10.                 out.flush();  
  11.         out.close();  
  12.     }  

这里需要获取WebApplicationContext ,获得了他就可以获取bean容器里面的bean了。 
如这里的user ,OK了!就这样!
Spring框架servlet可以通过Spring的依赖注入机制使用Spring管理的bean。通常,这可以通过实现`javax.servlet.ServletContainerInitializer`接口或者通过在web.xml配置`ContextLoaderListener`和`DispatcherServlet`来完成。 1. **使用`ContextLoaderListener`**: 当web应用启动时,`ContextLoaderListener`会初始化Spring的根`WebApplicationContext`。这个上下文包含了定义在Spring配置文件的所有bean。在servlet,你可以通过`WebApplicationContextUtils`类来获取这个根上下文,然后从检索所需的bean。 2. **使用`DispatcherServlet`**: `DispatcherServlet`是Spring提供的一个servlet,它在web层作为前端控制器,负责请求的路由和分发。与`ContextLoaderListener`类似,`DispatcherServlet`会初始化自己的`WebApplicationContext`,这个上下文包含了与web层相关的bean,例如控制器、视图解析器等。servlet可以作为`DispatcherServlet`的一部分被Spring管理,从而直接使用其上下文的bean。 3. **通过注解注入**: 如果你的Servlet是一个Java类,并且已经通过Spring注解或者XML配置成为了Spring容器的一个bean,那么你可以通过`@Autowired`、`@Inject`等注解直接注入你需要使用的其他bean。 4. **编程式使用**: 在Servlet的代码,可以通过调用`WebApplicationContext`的`getBean`方法来直接获取需要的bean。通常这需要使用`ServletContext`来获取`WebApplicationContextUtils`提供的`getWebApplicationContext`方法。 下面是一个例子,展示如何在servlet通过`WebApplicationContextUtils`获取Spring管理的bean: ```java @WebServlet("/myServlet") public class MyServlet extends HttpServlet { private MyService myService; public void init(ServletConfig config) { super.init(config); ServletContext servletContext = config.getServletContext(); WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext); if (context != null) { myService = context.getBean(MyService.class); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 使用myService执行业务逻辑 } } ``` 在这个例子,`MyService`是由Spring管理的一个bean。在servlet的`init`方法,我们通过`WebApplicationContextUtils`获取了根`WebApplicationContext`,然后从检索了`MyService`的bean实例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值