现在的位置: 首页Web开发>正文
如何使用spring将service层注入到servlet中去
2013年03月14日 Web开发 暂无评论 ⁄ 被围观 5,775 views+

Title: how to use Spring to inject ur service layer into the servlet .

 

In a typical struts+spring framework, we know how to inject our “service” into the “action”. But sometime we have to use the “servlet”.

I mean the real servlet, not the struts’s action-servlet!

For example:

We have a servlet name is “UserServlet”, we want to inject the service “MyTaskService” into it as following sample shows:

public class userServlet extends HttpServlet {

@Resource
MyTaskService myTaskService;
}

We will have two method:

Method 1:

we can directly override the servlet’s “init” method as following sample:

public void init(ServletConfig servletConfig) throws ServletException {
ServletContext servletContext = servletConfig.getServletContext();
WebApplicationContext webApplicationContext = WebApplicationContextUtils.
getWebApplicationContext(servletContext);
AutowireCapableBeanFactory autowireCapableBeanFactory =
webApplicationContext.getAutowireCapableBeanFactory();
autowireCapableBeanFactory.configureBean(this, BEAN_NAME);
}

The “BEAN_NAME” is the name which we want to inject thru the Spring, e.g. “MyTaskService”.

But this is not a graceful method.

Method 2:

We write a Delegate Bean, like the “org.springframework.web.struts.DelegatingRequestProcessor” , then we can thru configurable method to inject our service into the servlet, here is our Delegate Bean:

public class DelegatingServletProxy extends GenericServlet {
private String targetBean;
private Servlet proxy;

@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
proxy.service(req, res);

}

public void init() throws ServletException {
this.targetBean = getServletName();
getServletBean();
proxy.init(getServletConfig());
}

private void getServletBean() {
WebApplicationContext wac = WebApplicationContextUtils
.getRequiredWebApplicationContext(getServletContext());
this.proxy = (Servlet) wac.getBean(targetBean);
}
}

With this DelegatingServletProxy, we should make a little change of the “” cofig in our “web.xml”.

Normally, we config our “servlet” like this:

userServlet
com.sample.UserServlet

Now, we config our “servlet” in this way:

userServlet
com.sample.DelegatingServletProxy

No changes for “”, only for “”.

And the last thing is:

Pls don’t forget to add the “@Component” into the “servlet” to tell ur Spring container that this servlet will be regarded as a “spring-bean”. Here is a sample:

@Component
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Resource
MyTaskService myTaskService;
}

Ok, done, now we can enjoy the “IoC” into our servlet.



给我留言

留言无头像?


无觅相关文章插件,快速提升流量