Reputation: 5634
I am working on application which contains few sub modules. On one of these modules I have service with header like this:
@Transactional
@Service("mySimpleService")
public class MySimpleServiceImpl implements MySimpleService {}
On the another module I have a controller in which I would like to use one of the MySimpleService method. So I have something similar to this:
@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;
}
}
On the line mav.addObject(”name”, mySimpleService.getObject());
I am getting NullPointerException
. I don't know why. I am not getting error similar to Could not autowire field
but only NullPointerException
.
I have also created my own interceptor in this way to check some another ideas in my task:
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;
}
}
This interceptor is of course declared in dispatcher servlet. In my logs I can see NullPointerException
at line: request.setAttribute("attr", mySimpleService.getAttribute());
. So this is exactly problem with getting access to service from another application module.
How can I achieve this?
I have heard about ideas like building EJB with my service and share it using JNDI
or using Maven - copy folder with my service to target module during building application. I have tried to do the second option but it isn't working and I can't check if the coping was successful. Is possible to check Maven based solution? Do you have another suggestions?
EDIT
This is component scaning from target module dispatcher servlet:
<context:component-scan base-package="my.package.target.module.controller" annotation-config="false"/>
Upvotes: 3
Views: 11694
Reputation: 7952
I think your problem is the annotation-config="false". The annotation-config feature is what turns on the @Autowired annotation. Without auto-wiring, your mySimpleService properties do not get injected and remain null. Then you get the NullPointerException.
Try
<context:component-scan base-package="my.package.target.module.controller" annotation-config="true"/>
BTW - I have never used this exact configuration, since I don't do scanning. I always use the separate element:
<context:annotation-config />
Upvotes: 5