Servlet+spring 在servlet中注入spring

2017-08-09  本文已影响0人  师襄

不讲前言,也无后语,只记录一下实现及注意点。

在servlet+spring项目中,想在servlet类里面注入spring bean有以下两种方式:

1,复写servlet的init方法,如下

注意://支持@Autowired和@Resource方式注入bean,但注入的bean只能通过注解方式实例化(context:component-scan),不能通过xml 这种方式。

@Override

 public void init() throws ServletException {

    super.init();

    WebApplicationContextUtils.getWebApplicationContext(getServletContext())

    .getAutowireCapableBeanFactory().autowireBean(this);

}

2,复写servlet init(ServletConfig config)方法

注意://仅支持@Autowired方式注入bean,但不限bean实例化方式(xml <bean /> ,注解方式)

@Override

 public void init(ServletConfig config) throws ServletException {

super.init(config);

SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,

config.getServletContext());

}

pom.xml需引入servlet及spring相关的包

javax.servlet servlet-api 3.0

org.springframework spring-core 3.1.2.RELEASE

org.springframework spring-webmvc 3.1.2.RELEASE

org.springframework spring-beans 3.1.2.RELEASE

org.springframework spring-context 3.1.2.RELEASE

org.springframework spring-aop 3.1.2.RELEASE

org.springframework spring-tx 3.1.2.RELEASE

org.springframework spring-orm 3.1.2.RELEASE

最后,如果觉得在每个servlet里面重写init方法麻烦,可以建一个BaseServlet继承HttpServlet复写init方法,其他servlet继承BaseServlet即可。

上一篇 下一篇

猜你喜欢

热点阅读