Java development specification

metadata start

 

important:

Before submitting code each time, be sure to use the idea tool to format the code shortcuts Ctrl+Alt+L and Ctrl+Alt+O

 

Specifications & Rules

1 Naming conventions

Project directory structure

├── main

│   ├── java

│   │   └── com.paic.loancloud.config

│   │        └─ user

│ │ ├── mapper     \\mapper package, which mainly stores database operation classes, equivalent to the previous dao

│   │               │   └── UserMapper.java

│   │               ├── model

│ │ │ ├── entity    \\ corresponds to the table structure in the database

│   │               │   │   └── User.java

│ │ │ └── form      \\ corresponds to the json or form submitted by the HTTP request

│   │               │       └── UserForm.java

│ │ │ └── json       \\ corresponding to the json returned by HTTP

│   │               │       └── UserJson.java

│ │ ├── service       \\ business processing layer

│   │               │   ├── UserService.java

│ │ │ └── impl      \\ Business processing implementation layer

│   │               │       └── UserServiceImpl.java

│ │ └── web           \\ REST layer

│   │                   └── UserRest.java

│ └── resources                     \\ Application resource directory

│       └── mapper                    \\sql map

│             └── UserMapper.xml

└── test                              \\ test case directory

    ├── java

    │   └── com.paic.loancloud.config

    │         └── user

    │               └── mapper

    │               └── web

    │               └── service

    │                   └── TestUserService.java

    └── resources

        ├──  

            

            ├── application.properties

         

1.1 package naming

Format com.paic.loancloud.[component name].[subcomponent name]

for example:

   com.paic.loancloud.config.xxx

1.2 Java object name, member variable name, method name

 Follow the camel case rules commonly used in Java.

 

 Class names capitalize the first letter of each word (except for special meaning abbreviations).

 

 The first letter of the member variable name is lowercase, and the first letter of each other word is uppercase (except for special meaning abbreviations), such as: lastLoginTime, password, username

 

 The method name is the same as the member variable name (except for special meaning abbreviations), such as: getUserInfo, updateUser

 

The service implementation class ends with Impl

 

1.3 Service interface method naming rules

  • The methods of the service layer should not be named with database keywords such as select, insert, etc.

According to the following specifications: (method names other than the following examples are not allowed)

removeXxx methods responsible for removing a single object return boolean

updateXxx methods responsible for updating a single object, returning boolean

addXxx The method responsible for adding a single object returns boolean

addOrUpdateXxx methods responsible for adding or updating a single object return boolean

saveXxx methods responsible for saving multiple objects return boolean or int as appropriate

The getXxx method responsible for querying a single object returns entity

queryXxx is a method responsible for querying multiple objects queryListOfXxxByXxx queryMapOfXxxByXxx

 

  • The method name of the mapper layer is the SQL ID of the mapper

1.4 Static constant names

 All uppercase words, each word separated by an underscore

 

 For example: CONN_URL, CONNECTION_PASSWORD

 

1.5 Test case naming

Test class name:

TestXXXXXX uses the class name of the Test+ test

The test case follows the format:

Method name: test_method_name_when_condition_then_result

  If you can't understand the meaning through the name, you need to make a Chinese comment, or write Chinese directly on the method name

Such as: test_getFieldStandardById_when_ the incoming ID is 1000_then_ the object exists

 

2 Layering Rules

2.1 Presentation control layer

 

  In the web package, add @RestController("xxxxx") to the class name and @RequestMapping(/xxx/xxx) to the class, and specify the request method, such as POST/GET

  Notice:

    1. Camel case is not allowed, all request paths are lowercase, such as "/user/list"

    2. If the path contains compound nouns, please separate them with underscores, such as "enterprise/enterprise_channel_relation"

      而不是"enterprise/enterprise/channel/relation"或"enterprise/enterpriseChannelRelation"

 

2.2 Business Logic Layer

  src:

  service package

  Include subpackage: impl

  Add @Service to the implementation class name

2.3 Data Persistence Layer

  src:

  mapper package

  resource:

     mapper package

Add the @Mapper annotation to the interface

If the query is a list, to limit the maximum number of lists, the default setting is 200

 

2.4 Entity layer

  src:

  model package

 Contains subpackages: form, entity, json

The form package is mainly used for parameters passed by the front end

entity mainly corresponds to the database table one-to-one

josn is mainly the returned data 

 

The primary key must be of type Long

3 Swagger usage rules

The system uses swagger as the api document generator. Both development and testing need to use swagger to test the system, so developers need to maintain swagger

swagger only targets the web layer

3.1 Annotation class

@Api ( description = "Field Standard System API" )

Description of each class

3.2 Labeling method

@ApiOperation ( value = "Get field list" , notes = "Get fieldStandard list data through a single query condition" , response = FieldStandardJson.class )

value method name

Notes method description

response represents the returned class

3.3 Annotation method input parameters

@ApiImplicitParam(name = "queryField", value = "模糊查询字段", required = true, dataType = "String", paramType = "body")

Describe the fields accordingly

3.4 Annotation method parameters

@ApiOperation ( value = "Get field list" , notes = "Get fieldStandard list data through a single query condition" , response = FieldStandardJson.class )

Mainly the response parameter, which is used to indicate the class to be returned, which can be displayed on the swagger ui
Our rest layer returns the ReturnJson class by default, why not write the ReturnJson class, because the data in ReturnJson is an object, and the specific details cannot be seen on swagger
Therefore, we need to specify the response ourselves

4 Exception Handling Specifications

4.1 Unified Exception Catching Mechanism

 Reference code GlobalExceptionHandler can uniformly capture exceptions thrown by the system and format the output exceptions

 Now two exceptions have been caught in the system, which can be supplemented later

 One is MethodArgumentNotValidException, the output is as follows:

 

{
  "resultCode": "-1",
  "resultMesg": "System exception, please contact the system administrator",
  "data": [
  {
    "exceptionName": "MethodArgumentNotValidException",
    "errorMessage": "ID cannot be empty",
    "fieldCode": "id",
    "rejectedValue": 0
  },
  {
    "exceptionName": "MethodArgumentNotValidException",
    "errorMessage": "Database field code length cannot exceed 50 characters",
    "fieldCode": "fieldCode",
    "rejectedValue ": "striffffffffffffffff'ffffffff'\"ffffffffffffffffffffffffffffffffffffng"
  }
  ]
}

The other is the global catch exception Exception , the output is as follows:

 

{
    "resultCode": "-1",
    "resultMesg": "系统异常, 请联系系统管理员",
    "data": [
    {
        "exceptionName": "HttpMessageNotReadableException",
        "errorMessage": "Could not read document: Unexpected character ('n' (code 110)): was expecting comma to se",
        "fieldCode": null,
        "rejectedValue": null
    }
    ]
}

 

5 Other rules

5.1 Tools

  String Utils: Use   org.apache.commons.lang3.StringUtils

  Collection Utils: Use  org.apache.commons.collections.CollectionUtils

5.2 Code formatting

 Use a unified idea default formatting style

5.3 Code review process

  1. After the code is written, self-refactoring, sorting out logic, interface annotation, and idea annotation.

 

  2. Through tool comparison and self-review, ensure file changes, prevent submission of useless code, test code, and irrelevant configuration.

 

  3. Before or after submitting the local branch, find at least one senior engineer to review the code, and take the initiative to explain the changes and the scope of influence.

 

  4. There are no compilation errors when starting a single test or starting a service's normal functions (such as logging in).

 

  5. Submit it to the person in charge of the CI tester, and proactively inform the scope of influence.

5.4 Rest layer error code definition

  1. Define the error code and the message content of the error code in ResponseCode.java, be careful not to add an exclamation mark.

 

  2. Declare the business meaning of the error code in the specific rest, such as XX_XX_FAIL, etc.

 

  3. Use error codes such as Return.fail(XX_XX_FAIL).

5.5 Encapsulation of interface parameters and returned objects

  1. It is forbidden to use Map < String , String > as query parameters or query return values, which is extremely readable.

 

  2. Generally, there are 3 or more parameters, which can be selectively abstracted into objects. Please encapsulate an XxxQueryParam or XxxParam as the parameter of the query interface. For example queryListOfXxx(XxxQueryParam params ) updateXxx(XxxParam params )

 

  3. The object that needs to be returned to the client should be protected according to the sensitivity or necessity of the attribute in the entity object, and a converter can be used to convert it into model.json.Xxx .

 

     For example model . entity . User --- "model . json . UserInfo UserInfo is an attribute that is a necessary attribute to be exposed. Converted via UserToUserInfoConverter.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326218863&siteId=291194637