获得spring注入的service对象
在action层大家都知道用注解就可以获取spring的bean
1.在非请求类型环境中,即非action,controller类中,通过传递request参数达到类似于在action层的获取bean方式
ApplicationContext ac= WebApplicationContextUtils. getRequiredWebApplicationContext(request.getSession().getServletContext());
TestService testService = (TestService) ac.getBean("TestService" );
2.在LISTENER监听器或spring定时任务,或JUNITTEST等其他有spring环境中,使用如下方式
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
TestService testService = (TestService) ac.getBean("TestService");
本文介绍了如何在非请求类型的环境中获取Spring注入的Service对象。包括通过传递request参数的方式及在监听器、定时任务或单元测试等场景下使用ClassPathXmlApplicationContext获取Bean的方法。
977

被折叠的 条评论
为什么被折叠?



