Servlet+spring 在servlet中注入spring bean

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

在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即可。


最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容