欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JSP 开发之servlet中调用注入spring管理的dao

程序员文章站 2023-01-04 09:11:17
jsp 开发之servlet中调用注入spring管理的dao 我们用spring的依赖注入可以将dao注入到action中,然后我们就可以直接调用了dao中的方法了,可...

jsp 开发之servlet中调用注入spring管理的dao

我们用spring的依赖注入可以将dao注入到action中,然后我们就可以直接调用了dao中的方法了,可是servlet不是由spring容器管理,所以在servlet中不能注入dao类,也就不能用dao中的方法。

下面是实现方法:

private userdao userdao; 
   
    public void init() throws servletexception { 
    super.init(); 
     
    servletcontext servletcontext = this.getservletcontext(); 
     
    webapplicationcontext ctx = webapplicationcontextutils.getwebapplicationcontext(servletcontext); 
     
    userdao = (userdao)ctx.getbean("userdao"); 
  } 

在servlet中加入私有变量userdao,然后在servlet的init()方法中初始化一下即可用。

public userdao getuserdao() { 
    return userdao; 
  } 
 
  public void setuserdao(userdao userdao) { 
    this.userdao = userdao; 
  } 

还要加get  set方法,(去掉这个的情况没有测试)

以后就可以随意在servlet中调用dao了,耶!

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!