2012-10-18 83 views
1

我正在處理包含少量子模塊的應用程序。在這些模塊中的一個我有報頭的服務這樣的:如何在另一個模塊中自動裝配服務?

@Transactional 
@Service("mySimpleService") 
public class MySimpleServiceImpl implements MySimpleService {} 

在另一個模塊I具有控制器,其中我想使用MySimpleService方法之一。所以我有一些與此類似:

@Controller 
public class EasyController {  

    @Autowired 
    private MySimpleService mySimpleService; 

    @RequestMapping("/webpage.htm") 
    public ModelAndView webpage(@RequestParam, 
           @RequestParam, 
           HttpServletRequest request, 
           HttpServletResponse response) { 
     ModelAndView mav = new ModelAndView(」webpage」); 
     mav.addObject(」name」, mySimpleService.getObject()); 
     return mav; 
    } 
} 

在我得到NullPointerExceptionmav.addObject(」name」, mySimpleService.getObject());。我不知道爲什麼。我沒有得到類似於Could not autowire field的錯誤,但只有NullPointerException

我也創建了自己的攔截器以這種方式來檢查一些其他的想法在我的任務:

public class CustomInterceptor extends HandlerInterceptorAdapter { 

    @Autowired 
    private MySimpleService mySimpleService; 

    @Override 
    public boolean preHandle(HttpServletRequest request, 
          HttpServletResponse response, 
          Object handler) 
          throws Exception {   
     request.setAttribute("attr", mySimpleService.getAttribute()); 
     return true; 
    }  
} 

此攔截器在調度servlet的聲明當然。在我的日誌中,我可以看到NullPointerException在線:request.setAttribute("attr", mySimpleService.getAttribute());。所以這與從另一個應用程序模塊訪問服務完全相同。

我該如何做到這一點?

我聽說過使用我的服務構建EJB並使用JNDI分享它,或者在構建應用程序期間使用Maven-copy文件夾和我的服務對目標模塊進行分享。我試圖做第二個選擇,但它不工作,我不能檢查應對是否成功。是否有可能檢查基於Maven的解決方案?你有另外的建議嗎?

編輯

這是從目標模塊調度Servlet組件scaning:

<context:component-scan base-package="my.package.target.module.controller" annotation-config="false"/> 
+0

你是如何加載你的豆?使用'context:package-scan'或者它們是否都被定義在某個'* ApplicationContext'加載的xml文件中? – Alex

+0

@Alex:我編輯了我的問題,並添加了來自目標模塊調度程序servlet的行。我正在使用,你可以看到'context:component-scan'。 – woyaru

+0

嘗試添加'@Qualifier(「mySimpleService」)'註釋並檢查發生了什麼。另外,設置@Autowired(required = true)'。這會給你更好的調試 –

回答

3

我覺得你的問題是註解配置= 「假」。註釋配置功能是啓用@Autowired註釋的功能。如果沒有自動佈線,mySimpleService屬性不會被注入並保持爲空。然後你得到NullPointerException。

嘗試

<context:component-scan base-package="my.package.target.module.controller" annotation-config="true"/> 

順便說一句 - 我從來沒有用過這種精確配置,因爲我沒有做掃描。我總是使用單獨的元素:

<context:annotation-config /> 
+0

我必須檢查一下。將'annotation-config'設置爲true會導致包含'AutowiredAnnotationBeanPostProcessor'和'CommonAnnotationBeanPostProcessor'。此時此刻我不知道這是否適合我的申請。我會檢查。 – woyaru

+0

太棒了!它正在工作。我現在必須檢查這些'PostProcesssors'的問題。我會在這裏通知它。 – woyaru

相關問題