簡體   English   中英

如何在另一個模塊中自動接線服務?

[英]How to autowire service in another module?

我正在研究包含幾個子模塊的應用程序。 在這些模塊之一上,我可以通過以下標題提供服務:

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

在另一個模塊上,我有一個控制器,我想在其中使用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;
    }
}

mav.addObject(”name”, mySimpleService.getObject()); 我正在獲取NullPointerException 我不知道為什么 我沒有收到類似於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中聲明。 在我的日志中,我可以在以下行看到NullPointerExceptionrequest.setAttribute("attr", mySimpleService.getAttribute()); 因此,這確實是從另一個應用程序模塊訪問服務的問題。

我該如何實現?

我聽說過一些想法,例如使用我的服務構建EJB並使用JNDI或使用Maven共享它-在構建應用程序期間使用我的服務將文件夾復制到目標模塊。 我試圖做第二種選擇,但它不起作用,我無法檢查應對是否成功。 可以檢查基於Maven的解決方案嗎? 您還有其他建議嗎?

編輯

這是從目標模塊調度程序servlet進行的組件掃描:

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

我認為您的問題是注釋配置=“ false”。 注解配置功能是打開@Autowired注解的功能。 如果不進行自動裝配,則不會注入mySimpleService屬性,並且這些屬性將保持為空。 然后,您將獲得NullPointerException。

嘗試

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

順便說一句-我從未使用過這種確切的配置,因為我不進行掃描。 我總是使用單獨的元素:

<context:annotation-config />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM