Spring Mvc那点事---(37)rest服务项目模块介绍

引子

   一个项目通常要包括几个模块,服务层,业务层,数据层,实体类,每个模块单独一个项目,降低了项目之间的耦合性,增强了项目的清晰度,减少各个项目之间的依赖。所以越是大的项目,项目模块分的越多,层次分的越清晰。对于新加入的同伴,对项目熟悉越快,上手越快,同时每个人可以单独管理一个模块,分工明确,互不影响。

项目架构

    废话少说,直接上图,看看下面的项目结构图
  
 上面的项目是一个完整的spring mvc rest服务项目架构,  数据层,服务层,业务层,每层分为两个模块,接口模块和实现模块。上层调用下层只调用下层的接口,通过spring注解自己去发现接口实现。
项目是rest服务通过mybatis组件向mysql数据库插入数据,   erp-webapp是启动项目,也就是宿主项目,rest-api和rest-impl是服务层的接口和接口实现, service-api和service-impl是业务层的接口和接口实现.
dao-api是数据操作层接口,  dao-mybatis是mybatis的配置文件, erp-common是项目的通用操作类。

服务实现

  @RestController用来标注是controller,
 @RequestMapping用来设置请求别名,请求方式和请求动作。
spring mvc启用扫描使用如下配置
<context:component-scan base-package="org.supersoft.erp.rest.impl" />    
 <context:annotation-config />
   客户端和服务端数据传输使用json,可以使用spring内置的json组件,org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
   可以看如下服务代码
package org.supersoft.erp.rest.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.supersoft.erp.common.CommonResponse;
import org.supersoft.erp.common.ServiceResponse;
import org.supersoft.erp.domain.Product;
import org.supersoft.erp.rest.api.ProductController;
import org.supersoft.erp.rest.dto.ProductDto;
import org.supersoft.erp.service.api.ProductService;


@RestController
@RequestMapping("product")
public class ProductControllerImpl implements ProductController {

    @Autowired
    private ProductService productService;

    /**
     * 添加
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    @ResponseBody
    public CommonResponse<?> addProduct(@RequestBody ProductDto product) {
        try
        {
            Product p=new Product();
            BeanUtils.copyProperties(product, p);
            productService.addProduct(p);
            return CommonResponse.result();
        }
        catch(Throwable t)
        {
            return CommonResponse.error();
        }
    }

    /**
     * 修改
     */
    public CommonResponse<?> updateProduct(@RequestBody ProductDto product) {
        try
        {
            Product p=new Product();
            BeanUtils.copyProperties(product, p);
            productService.updateProduct(p);
            return CommonResponse.result();
        }
        catch(Throwable t)
        {
            return CommonResponse.error();
        }
    }

}


使用tomcat启动webapp服务。
客户端调用可以使用浏览器自带的请求组件进行测试,这里使用谷歌浏览器的DHC


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章