在控制器或服务中将业务逻辑放在何处?

时间:2019-07-20 06:24:14

标签: java spring-mvc spring-data-jpa

我正在开发Spring Web MVC应用程序。我有与CRUD或复杂操作有关的查询。

我的问题是在控制器层或服务层中将我们的逻辑放在哪里?

当前,我正在用控制器编写所有代码,并在save()中调用delete()的{​​{1}}或service方法。

请参见下面的代码示例。请帮助我找到正确的编码方式。

控制器级别:

controller
@Controller
@RequestMapping(value = "/Shipping")
public class ShippingController {

 @Autowired
 private ShippingService shippingService;


 @RequestMapping(value = "/addNewShippingMethod/{id}", method = RequestMethod.POST)
 public String addshippingMethod(@PathVariable("id") String id, HttpServletRequest request) {
     Shipping shipping=new Shipping();
     shipping.setName(request.getParameter("name"));
     shippingService.save(shipping);
     return "/Shipping/ShippingMethodList";
    }
}

服务水平:

@Service
public class ShippingService {
 @Autowired
 private ShippingMethodRespository shippingMethodRespository;

 public ModelAndView saveShippingMethod(HttpServletRequest request, String id) {    
     shippingMethodRespository.save(shipping);
 }
}
@Controller
@RequestMapping(value = "/Shipping")
        public class ShippingController {

        @Autowired
        private ShippingService shippingService;

        @RequestMapping(value = "/addNewShippingMethod/{id}", method = RequestMethod.POST)
        public ModelAndView addshippingMethod(@PathVariable("id") String id, HttpServletRequest request) {

            return shippingService.saveShippingMethod(request, id);
        }
}

我已经描述了这两种情况,第一个是:我们保存控制器中的所有数据并返回页面。

第二个是:使用控制器进行重定向和写入逻辑,并将数据保存在服务层中。

您能告诉我哪种方法是最好的代码吗?

1 个答案:

答案 0 :(得分:0)

是的,您可以收集有关何时使用服务层的一些知识?您可以以Use of Service Layer stack overflow Implementing Business Logic from docs.oracle.com开头。

现在,如果我们看一下您的问题中提到的两种方法,那么这表示在第一种情况下,“不应该在Controller中编写业务逻辑”。

所以绝对我赞成第二部分,因为当您具有服务层时,您应该在那儿编写业务逻辑。

@Controller
@RequestMapping(value = "/Shipping")
        public class ShippingController {

        @Autowired
        private ShippingService shippingService;

        @RequestMapping(value = "/addNewShippingMethod/{id}", method = RequestMethod.POST)
        public ModelAndView addshippingMethod(@PathVariable("id") String id, HttpServletRequest request) {

            return shippingService.saveShippingMethod(request, id);
        }
}
@Service
public class ShippingService {
     @Autowired
     private ShippingMethodRespository shippingMethodRespository;

     public ModelAndView saveShippingMethod(HttpServletRequest request, String id) {
        Shipping shipping=new Shipping();
        shipping.setName(request.getParameter("name"));
        shippingMethodRespository.save(shipping);
        ModelAndView shippingMethodsPage = new 
        ModelAndView("/Shipping/ShippingMethodList");
        return shippingMethodsPage;
    }    
}