1. 程式人生 > >Spring通過上下文獲取bean

Spring通過上下文獲取bean

  • 問題描述:

 某處呼叫get方法,卻報空指標異常。經查,是dao物件為null。再查,是service物件為newInstance,並沒有注入dao物件。因此修改語句,從spring中獲取service物件。

  • 修改過程:

已有引數:Class<T> service

最終目標:T sv

1. sv由spring上下文context獲取

T sv = context.getBean(service);

2. ApplicationContext context由WebApplicationContextUtils獲取

ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);

此處說明:不可使用FileSystemXmlApplicationContext等物件初始化,需要獲取的是目前使用中的context

3. ServletContext sc由ContextLoader獲取

ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();

此處說明:如有request引數,也可使用request.getServletContext();獲取

  • 最終程式碼:
    ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();
    ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
    T sv = context.getBean(service);