Servlet中使用Spring bean或自动织入

本文探讨了在Servlet中使用@Autowired注解进行依赖注入时遇到的问题及解决办法。由于Servlet由Servlet容器管理而非Spring直接管理,直接使用@Autowired无法生效。文章提供了两种解决方案:一是通过init方法使用Spring工具类获取Bean;二是利用自动织入配合SpringBeanAutowiringSupport进行注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:

在Servlet中,如果像在其他服务类中一样使用@Autowired注解,则达不到自动注入的效果,例如:

public class OneDemoServlet extends HttpServlet{
        /**
	 * 
	 */
	private static final long serialVersionUID = 121334411244623232133L;
	
	@Autowired
	OneClient oneClient;	 
	
 	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		doPost(req, resp);
	}	

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		String actionType = req.getParameter("action");
                if(xxx.equals(actionType)){
                     oneClient.doSomething();
                }
                //...
       }
}
	

原因:

“在应用中一般普通的JavaPojo都是由spring来管理的,所以使用autowire注解来进行注入不会产生问题,但是有两个东西是例外的,一个是 Filter,一个是Servlet,这两样东西都是由Servlet容器来维护管理的,所以如果想和其他的Bean一样使用Autowire来注入的 话,是需要做一些额外的功夫的。
对于Filter,Spring提供了DelegatingFilterProxy”。

参考:http://blog.youkuaiyun.com/axzywan/article/details/8056892


解决:

在Servlet的init()初始化方法中获取Beand对象。

方法一:使用Spring工具类获取bean。

OneClient oneClient;    

public void init(ServletConfigconfig) throws ServletException { 

        super.init(config); 

        ServletContext servletContext = this.getServletContext();

        WebApplicationContext wac = null;

        wac = WebApplicationContextUtils

                .getRequiredWebApplicationContext(servletContext);

                udsClient = (UdsClient)wac.getBean("oneClient");

        System.out.println("oneClient:" +oneClient);

 

 

方法二:使用自动织入

       @Autowired

     OneClient oneClient;      

    public void init(ServletConfigconfig) throws ServletException { 

        super.init(config); 

        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(

                      this,config.getServletContext()); 

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值