当前位置:编程学习 > JAVA >>

【高分】Servlet中用Annotation注入bean

可能是个老生常谈的问题,无奈网上的解决办法完全不好使,无奈提问!
项目中需要在Servlet中调用Service,由于项目框架全面使用了Annotation,以前使用的从ApplicationContext中getBean的方法也不好使了(也不愿意使,否则又得在xml中定义一堆的bean)。

几天来度娘、Google了无数solution,解决方式五花八门,但就是没有一个好使的!
1. 
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
testService = (TestService)ctx.getBean("testService");
结果:传统的xml配置bean方式可以,Annotation方式失败,testService为空!

2.
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
结果:testService为空!

3.web.xml中TestServlet申明中servlet-class的值改为org.springframework.web.context.support.HttpRequestHandlerServlet,TestServlet
结果:tomcat启动报错找不到TestServlet

项目结构非常简单,一共3个类TestServlet,TestService,TestController,
TestService类加了@Service注释
TestController和TestService中注释申明了TestServcei:
@Resource(换成@Autowire也一样没用)
private TestService testService;
spring-servlet.xml中配置了:
<mvc:annotation-driven />
<context:component-scan base-package="com.test" />

TestController可以成功调用TestService,但TestServlet死活不行

敢问哪位大哥实际在Servlet中用注解方式成功注入过bean的,网上五花八门的办法说的有鼻子有眼的,不像是忽悠呀,为毛到我这就不好使了???

Servlet Spring 注入 --------------------编程问答-------------------- 一个是web容器,一个是spring容器,我遇到的时候是在xml中定义bean,看网上的方法基本没有使用注解的 --------------------编程问答-------------------- 已放弃使用Servlet,看样子spring压根就不想让我们又用注解又用servlet了。ps:我用servlet只是出于以前开发项目的一个“陋习”,用servlet来载入一些静态数据到缓存里。查了一些资料改用ApplicationListener了,目测这个才是正道。晚些结贴,看看还有没有类似有价值的讨论。 --------------------编程问答-------------------- servlet 还没见过有注解这一说
用action把servlet替了吧,要不看的都头疼 --------------------编程问答-------------------- servlet 还没见过有注解这一说
用action把servlet替了吧,要不看的都头疼 
=================================
看我回复,我用servlet纯粹是拿它的init方法来加载一些数据,俺还不至于变态到用springmvc又用servlet来处理请求的地步。。。 --------------------编程问答-------------------- 公司项目基本不用注解、、 --------------------编程问答-------------------- ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
你自己遍历一下ctx中的bean吧~里面应该有sessionfactory!然后你自己new 一个dao,手动把sessionfactory放进去,这样你的dao就可以用了。目前我就是用这个方法初始化数据的,直接跳过service层吧!
补充:Java ,  Web 开发
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,