特殊情况一:ActionForm
思路有两种:
第一种:将你需要注入的参数设置为static的,然后将设值方法setXXX的返回值设置为非void型,比如你的
protected IDaoService daoService;
改为
protected static IDaoService daoService;
设值方法setXXX,为:
public static boolean setDaoService(IDaoService daoService) {
LookuserForm.daoService = daoService;
return true;
}
然后在spring配置文件中设值:
<bean id="BaseBoolean"
class="org.shan.student.form.LookuserForm"
factory-method="setDaoService"
depends-on="daoService">
<constructor-arg ref="daoService"></constructor-arg>
</bean>
这样就实现了daoService的注射。class就是你的ActionForm的类,factory-method就是你的非void型注入对象的方法,depends-on就是你要注入对象使用的bean,constructor-arg ref="XXX"也是一样了。
第二种:重写ActionForm的public void setServlet(ActionServlet servlet)方法。
public void setServlet(ActionServlet servlet) {
ServletContext context = servlet.getServletContext();
ApplicationContext ctx =WebApplicationContextUtils.getWebApplicationContext(context);
LookuserForm temp = (LookuserForm) ctx.getBean("LookuserForm");
this.daoService = temp.getDaoService ();
super.setServlet(servlet);
}
特殊情况二:servlet中获取在Servlet(或者Filter,或者Listener)中使用spring的IOC容器默认情况下Servlet容器创建spring容器对象,注入到servletContext中,servletContext对象又是注入到session对象中,session对象又是注入到request对象中,request对象又是注入到servlet对象中,(其实不是很标准的注入,是传参数,或者对属性直接付值)。层层依赖可以得到spring容器对象。
ServletContext servletContext = request.getSession().getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
UsersManager um = (UsersManager)ctx.getBean( "UserManager");