天天看點

Spring Bean 注入 Servlet 的方法Andy Kayley's Blog

不使用任何知名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: java, spring, servlet, dependency injection, andy kayley