Spring将代码从控制器移动到服务

时间:2015-02-23 13:54:16

标签: java spring spring-mvc service controller

我刚接触春天,并希望将我的工作代码从控制器移到服务中以获得最佳实践,但现在我得到了:

SEVERE: Servlet.service() for servlet [mvc-dispatcher] in context with path [/xls] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause java.lang.NullPointerException

MainController.java

public class MainController {
  private ListServiceImpl listServiceImpl;
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
     public ModelAndView upload(@RequestParam("myfile") MultipartFile myFile)  throws IOException {
    InputStream inputStream = myFile.getInputStream();
    ModelAndView model = new ModelAndView("list");
    model.addObject("list", listServiceImpl.getList(inputStream) );
  return model; 
}

ListServiceImpl.java

@Service
public class ListServiceImpl implements ListService {
  @Override
  public List<UserAndSum> getList(InputStream inputStream) {
  List <UserAndSum> list25plus25 = new ArrayList<UserAndSum>();
  Workbook workBook = Workbook.getWorkbook(inputStream);
  ..............
  list25plus25 .add(new UserAndSum(previousUser, sum));
return list25plus25;
}

2 个答案:

答案 0 :(得分:0)

listServiceImpl永远不会启动或接线。

因此,您必须在NullPointerException课程的这一行中获得MainController

model.addObject("list", listServiceImpl.getList(inputStream) );

如果您想通过Spring进行管理,则必须添加@Autowire注释。

顺便说一下。如果你有接口使用它们:

@Autowired
private ListService listService; //refers to the interface

答案 1 :(得分:0)

@Autowire添加到ListService,然后使用它。

@Autowire
private ListService listService;

listService.getList(inputStream)

如果您使用的是基于XML的配置,

listService = context.getBean("listService");  // listService is your bean name