Spring Bean 注入 Servlet 的方法

不使用任何知名MVC框架,仅用Servlet+jsp完成View层的开发。基于接口开发测试,要集成Spring+Hibernate,遇到Spring Bean注入Servlet的问题。

在applicationContext.xml中定义数据层访问Bean:

<bean id="userDao" class="test.UserDaoImpl"></bean>

UserDaoImpl是一个使用Hibernate访问数据库的类,包括了一些简单增删改查的方法,如getAll(),save()等

MyServlet.java代码如下:

public class MyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private UserDao userDao;

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public MyServlet() {
		super();
	}

	public void init(ServletConfig config) throws ServletException {
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		List<User> list = userDao.getAll();
		out.println("<html>");
		out.println("<body>");
		out.println("<pre>ID\tNAME");
		for (User u : list) {
			out.println(u.getUserId() + "\t" + u.getUserName());
		}
		out.println("</pre>");
		out.println("</body>");
		out.println("</html>");
		out.close();
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}
}
很显然,如果不加处理,下面这一行一定会抛出java.lang.NullPointerException。

		List<User> list = userDao.getAll();

解决方法一:

在Servlet的init方法中增加以下代码,即可通知Servlet在启动时,自动查找userDao Bean并装配。

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

可是下面这一行需要将Bean Name硬编码到java源码中,让我很不爽。

autowireCapableBeanFactory.configureBean(this, "userDao");

解决办法二(推荐):

还是在Servlet的init方法中增加以下代码。

	public void init(ServletConfig config) throws ServletException {
	    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
	    	      config.getServletContext());
	}
并且在变量userDao上一行增加@Autowired
	@Autowired
	private UserDao userDao;

这样,就不用硬编码Bean Name到java源码中了。

后续:

本文主要解决的是在Servlet注入Spring Bean,对于在Servlet中载入Spring Bean的方法不在考虑范围之内。

还有一些文章写的太抽象,我没能看懂:-(:

1、http://blog.csdn.net/lifetragedy/article/details/6320428

2、http://andykayley.blogspot.com/2008/06/how-to-inject-spring-beans-into.html

由于该文章寄存在blogspot.com,不幸被伟大的党“河蟹”了。所以贴在这里,期盼谁能够帮助解释一下!

Andy Kayley's Blog

http://andykayley.blogspot.com/2008/06/how-to-inject-spring-beans-into.html

How to Inject Spring Beans into Servlets Revisited.

Back in November I wrote a post about How to Inject Spring Beans into Servlets, since then one of the comments made on the post by angel, mentioned an interface and Servlet that comes with spring that does this the proper spring way. Thank you very much angel, this is what I was looking for before I wrote the last post :)

The proper way how this should be achieved is to write a class that implements HttpRequestHandler and define this class in your applicationContext.xml. Then you define a servlet in web.xml with a class of HttpRequestHandlerServlet and make sure the name of the servlet is the same as the bean you defined in applicationContext.xml.

First lets write a class that we want to inject into a servlet...
Next we'll write a class that implements the HttpRequestHandler this is basically our servlet.Next all we need to do is configure our web.xml and applicationContext.xml...First applicationContext.xml...And finally configure your web.xml ...Now run your web app and go to http://localhost:8080/MyServlet
You should see in your console log the output of your injected servlet...

******* HELLO *******
someMethod called

Brilliant :-) Thanks again angel.

Technorati Tags: , , , ,

 
 
 

                
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值