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 byangel, 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 ofHttpRequestHandlerServlet 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: java, spring, servlet, dependency injection, andy kayley





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章