diff --git a/LICENSE b/LICENSE
new file mode 100644
index 000000000..261eeb9e9
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/README.md b/README.md
index 61d882d78..c80190b98 100644
--- a/README.md
+++ b/README.md
@@ -1,13 +1,14 @@
-
-[](https://github.com/lihengming/spring-boot-api-project-seed/releases)
+[](http://www.apache.org/licenses/LICENSE-2.0.html)
+[](https://github.com/lerry903/spring-boot-api-project-seed/releases)
## 简介
-Spring Boot API Project Seed 是一个基于Spring Boot & MyBatis的种子项目,用于快速构建中小型API、RESTful API项目,该种子项目已经有过多个真实项目的实践,稳定、简单、快速,使我们摆脱那些重复劳动,专注于业务代码的编写,减少加班。下面是一个简单的使用演示,看如何基于本项目在短短几十秒钟内实现一套简单的API,并运行提供服务。
+Spring Boot API Project Seed 是一个基于Spring Boot & MyBatis的种子项目,用于快速构建中小型API、RESTful API项目,该种子项目已经有过多个真实项目的实践,稳定、简单、快速,使我们摆脱那些重复劳动,专注于业务代码的编写,减少加班。
-[](http://v.youku.com/v_show/id_XMjg1NjYwNDgxNg==.html?spm=a2h3j.8428770.3416059.1)
## 特征&提供
-- 最佳实践的项目结构、配置文件、精简的POM([查看项目结构图](https://github.com/lihengming/java-codes/blob/master/shared-resources/github-images/project-struct.png))
-- 统一响应结果封装及生成工具
+- 最佳实践的项目结构、配置文件、精简的POM
+- 统一响应结果封装
- 统一异常处理
+- 统一日志打印
+- 开源的Java工具包Hutool
- 简单的接口签名认证
- 常用基础方法抽象封装
- 使用Druid Spring Boot Starter 集成Druid数据库连接池与监控
@@ -27,19 +28,23 @@ Spring Boot API Project Seed 是一个基于Spring Boot & MyBatis的种子项目
## 开发建议
- 表名,建议使用小写,多个单词使用下划线拼接
- Model内成员变量建议与表字段数量对应,如需扩展成员变量(比如连表查询)建议创建DTO,否则需在扩展的成员变量上加```@Transient```注解,详情见[通用Mapper插件文档说明](https://mapperhelper.github.io/docs/2.use/)
-- 建议业务失败直接使用```ServiceException("message")```抛出,由统一异常处理器来封装业务失败的响应结果,比如```throw new ServiceException("该手机号已被注册")```,会直接被封装为```{"code":400,"message":"该手机号已被注册"}```返回,无需自己处理,尽情抛出
-- 需要工具类的话建议先从```apache-commons-*```和```guava```中找,实在没有再造轮子或引入类库,尽量精简项目
-- 开发规范建议遵循阿里巴巴Java开发手册([最新版下载](https://github.com/lihengming/java-codes/blob/master/shared-resources/%E9%98%BF%E9%87%8C%E5%B7%B4%E5%B7%B4Java%E5%BC%80%E5%8F%91%E6%89%8B%E5%86%8CV1.3.0.pdf))
+- 建议业务失败使用```BusinessException```子类抛出,由统一异常处理器来封装业务失败的响应结果,比如```throw new DataNotFoundException()```,会直接被封装为```{"code":50001,"message":"数据未找到"}```返回,无需自己处理,尽情抛出
+- 需要工具类的话建议先从```Hutool```中找,实在没有再继承```Hutool```中相应的工具类造轮子或引入类库,尽量精简项目
+- 开发规范建议遵循阿里巴巴Java开发手册([最新版下载](https://github.com/alibaba/p3c))
- 建议在公司内部使用[ShowDoc](https://github.com/star7th/showdoc)、[SpringFox-Swagger2](https://github.com/springfox/springfox) 、[RAP](https://github.com/thx/RAP)等开源项目来编写、管理API文档
## 技术选型&文档
-- Spring Boot([查看Spring Boot学习&使用指南](http://www.jianshu.com/p/1a9fd8936bd8))
+- Spring Boot([查看Spring Boot学习&使用指南](https://blog.csdn.net/lsy0903/article/category/6413992))
- MyBatis([查看官方中文文档](http://www.mybatis.org/mybatis-3/zh/index.html))
- MyBatisb通用Mapper插件([查看官方中文文档](https://mapperhelper.github.io/docs/))
- MyBatis PageHelper分页插件([查看官方中文文档](https://pagehelper.github.io/))
- Druid Spring Boot Starter([查看官方中文文档](https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter/))
- Fastjson([查看官方中文文档](https://github.com/Alibaba/fastjson/wiki/%E9%A6%96%E9%A1%B5))
+- Hutool工具包([查看官方文档](http://hutool.mydoc.io/))
- 其他略
## License
-无,纯粹开源分享,感谢大家 [Star](https://github.com/lihengming/spring-boot-api-project-seed/stargazers) & [Fork](https://github.com/lihengming/spring-boot-api-project-seed/network/members) 的支持。
+
+用户在遵循本项目协议的同时,如果用户下载、安装、使用本项目中所提供的软件,软件作者对任何原因在使用本项目中提供的软件时可能对用户自己或他人造成的任何形式的损失和伤害不承担任何责任。作者有权根据有关法律、法规的变化修改本项目协议。修改后的协议会随附于本项目的新版本中。当发生有关争议时,以最新的协议文本为准。如果用户不同意改动的内容,用户可以自行删除本项目。如果用户继续使用本项目,则视为您接受本协议的变动。
+
+感谢大家 [Star](https://github.com/lerry903/spring-boot-api-project-seed/stargazers) & [Fork](https://github.com/lerry903/spring-boot-api-project-seed/network/members) 的支持。
diff --git a/pom.xml b/pom.xml
index 80cf9affc..3a4d39ddf 100644
--- a/pom.xml
+++ b/pom.xml
@@ -10,14 +10,17 @@
jar
+ UTF-8
+ UTF-8
1.8
+ 1.1.10
org.springframework.boot
spring-boot-starter-parent
- 1.5.13.RELEASE
+ 1.5.14.RELEASE
@@ -83,11 +86,17 @@
fastjson
1.2.47
+
+
+ cn.hutool
+ hutool-all
+ 4.1.0
+
com.alibaba
druid-spring-boot-starter
- 1.1.10
+ ${druid.version}
@@ -102,6 +111,24 @@
1.3.5
test
+
+
+ org.projectlombok
+ lombok
+ 1.18.0
+
+
+
+ org.springframework.boot
+ spring-boot-devtools
+ runtime
+ true
+
+
+ org.aspectj
+ aspectjweaver
+ 1.8.13
+
diff --git a/src/main/java/com/company/project/EnvironmentEnum.java b/src/main/java/com/company/project/EnvironmentEnum.java
new file mode 100644
index 000000000..bc812c01f
--- /dev/null
+++ b/src/main/java/com/company/project/EnvironmentEnum.java
@@ -0,0 +1,35 @@
+package com.company.project;
+
+import org.springframework.core.env.Environment;
+import org.springframework.util.Assert;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 环境常量枚举类
+ * @author LErry.li
+ * Date: 2018-06-16
+ * Time: 14:43
+ */
+public enum EnvironmentEnum {
+ //开发
+ DEV,
+ //生产
+ PROD,
+ //联调
+ FE,
+ //测试
+ QA,
+ //仿真
+ STG;
+
+ public static boolean isProdEnv(Environment env) {
+ Assert.notNull(env, "env parameter not null.");
+ return EnvironmentEnum.PROD.name().equalsIgnoreCase(env.getProperty("spring.profiles.active"));
+ }
+
+ @Override
+ public String toString() {
+ return this.name();
+ }
+}
diff --git a/src/main/java/com/company/project/common/annotations/EnumValue.java b/src/main/java/com/company/project/common/annotations/EnumValue.java
new file mode 100644
index 000000000..331cd5dcf
--- /dev/null
+++ b/src/main/java/com/company/project/common/annotations/EnumValue.java
@@ -0,0 +1,83 @@
+package com.company.project.common.annotations;
+
+
+
+import com.company.project.common.exception.BusinessException;
+import com.company.project.common.util.StringUtil;
+
+import javax.validation.Constraint;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+import javax.validation.Payload;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 校验枚举值有效性
+ * @author LErry.li
+ * Date: 2018-06-15
+ * Time: 14:41
+ */
+@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
+@Retention(RetentionPolicy.RUNTIME)
+@Constraint(validatedBy = EnumValue.Validator.class)
+public @interface EnumValue {
+
+ String message() default "{custom.value.invalid}";
+
+ Class>[] groups() default {};
+
+ Class extends Payload>[] payload() default {};
+
+ Class extends Enum>> enumClass();
+
+ String enumMethod();
+
+ class Validator implements ConstraintValidator {
+
+ private Class extends Enum>> enumClass;
+ private String enumMethod;
+
+ @Override
+ public void initialize(EnumValue enumValue) {
+ enumMethod = enumValue.enumMethod();
+ enumClass = enumValue.enumClass();
+ }
+
+ @Override
+ public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
+ if (value == null) {
+ return Boolean.TRUE;
+ }
+
+ if (enumClass == null || enumMethod == null) {
+ return Boolean.TRUE;
+ }
+
+ Class> valueClass = value.getClass();
+
+ try {
+ Method method = enumClass.getMethod(enumMethod, valueClass);
+ if (!Boolean.TYPE.equals(method.getReturnType()) && !Boolean.class.equals(method.getReturnType())) {
+ throw new BusinessException(StringUtil.formatIfArgs("%s method return is not boolean type in the %s class", enumMethod, enumClass));
+ }
+
+ Boolean result = (Boolean)method.invoke(null, value);
+ return result == null ? false : result;
+ } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
+ throw new BusinessException(e.getMessage());
+ } catch (NoSuchMethodException | SecurityException e) {
+ throw new BusinessException(StringUtil.formatIfArgs("This %s(%s) method does not exist in the %s", enumMethod, valueClass, enumClass), e);
+ }
+ }
+
+ }
+
+}
diff --git a/src/main/java/com/company/project/common/annotations/ServiceLog.java b/src/main/java/com/company/project/common/annotations/ServiceLog.java
new file mode 100644
index 000000000..7a144e7b0
--- /dev/null
+++ b/src/main/java/com/company/project/common/annotations/ServiceLog.java
@@ -0,0 +1,22 @@
+package com.company.project.common.annotations;
+
+import java.lang.annotation.*;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * AOP日志记录,自定义注解
+ * @author LErry.li
+ * Date: 2018-06-17
+ * Time: 14:45
+ */
+@Target({ElementType.PARAMETER, ElementType.METHOD})
+@Retention(RetentionPolicy.RUNTIME)
+@Documented
+public @interface ServiceLog {
+
+ /**
+ * 日志描述
+ */
+ String description() default "";
+}
diff --git a/src/main/java/com/company/project/common/aspect/RestControllerAspect.java b/src/main/java/com/company/project/common/aspect/RestControllerAspect.java
new file mode 100644
index 000000000..cad9f7c6b
--- /dev/null
+++ b/src/main/java/com/company/project/common/aspect/RestControllerAspect.java
@@ -0,0 +1,84 @@
+package com.company.project.common.aspect;
+
+import com.company.project.common.exception.GlobalExceptionHandler;
+import com.company.project.common.util.IpUtil;
+import com.company.project.common.util.LogAspectUtil;
+import org.aspectj.lang.ProceedingJoinPoint;
+import org.aspectj.lang.annotation.Around;
+import org.aspectj.lang.annotation.Aspect;
+import org.aspectj.lang.reflect.MethodSignature;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+
+import javax.servlet.http.HttpServletRequest;
+import java.lang.reflect.Method;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ *
+ * @author LErry.li
+ * Date: 2018-06-16
+ * Time: 16:31
+ */
+@Aspect
+@Component
+public class RestControllerAspect {
+
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
+
+ /**
+ * 环绕通知
+ * @param joinPoint 连接点
+ * @return 切入点返回值
+ * @throws Throwable 异常信息
+ */
+ @Around("@within(org.springframework.web.bind.annotation.RestController) || @annotation(org.springframework.web.bind.annotation.RestController)")
+ public Object apiLog(ProceedingJoinPoint joinPoint) throws Throwable {
+ MethodSignature signature = (MethodSignature) joinPoint.getSignature();
+ Method method = signature.getMethod();
+
+ boolean logFlag = this.needToLog(method);
+ if (!logFlag) {
+ return joinPoint.proceed();
+ }
+ HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
+
+ String userAgent = request.getHeader("user-agent");
+ String ip = IpUtil.getRealIp(request);
+ String methodName = this.getMethodName(joinPoint);
+ String params = LogAspectUtil.getMethodParams(joinPoint);
+
+ logger.info("开始请求方法:[{}] 参数:[{}] IP:[{}] userAgent [{}]", methodName, params, ip, userAgent);
+ long start = System.currentTimeMillis();
+ Object result = joinPoint.proceed();
+ long end = System.currentTimeMillis();
+ String deleteSensitiveContent = LogAspectUtil.deleteSensitiveContent(result);
+ logger.info("结束请求方法:[{}] 参数:[{}] 返回结果[{}] 耗时:[{}]毫秒 ",
+ methodName, params, deleteSensitiveContent, end - start);
+ return result;
+ }
+
+ private String getMethodName(ProceedingJoinPoint joinPoint) {
+ String methodName = joinPoint.getSignature().toShortString();
+ String shortMethodNameSuffix = "(..)";
+ if (methodName.endsWith(shortMethodNameSuffix)) {
+ methodName = methodName.substring(0, methodName.length() - shortMethodNameSuffix.length());
+ }
+ return methodName;
+ }
+
+
+ /**
+ * 判断是否需要记录日志
+ */
+ private boolean needToLog(Method method) {
+ return method.getAnnotation(GetMapping.class) == null
+ && !method.getDeclaringClass().equals(GlobalExceptionHandler.class);
+ }
+
+}
diff --git a/src/main/java/com/company/project/common/aspect/ServiceLogAspect.java b/src/main/java/com/company/project/common/aspect/ServiceLogAspect.java
new file mode 100644
index 000000000..c9b8c24a2
--- /dev/null
+++ b/src/main/java/com/company/project/common/aspect/ServiceLogAspect.java
@@ -0,0 +1,94 @@
+package com.company.project.common.aspect;
+
+import com.company.project.common.annotations.ServiceLog;
+import com.company.project.common.util.LogAspectUtil;
+import org.aspectj.lang.ProceedingJoinPoint;
+import org.aspectj.lang.annotation.Around;
+import org.aspectj.lang.annotation.Aspect;
+import org.aspectj.lang.reflect.MethodSignature;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import java.lang.reflect.Method;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * service 日志记录切面
+ *
+ * @author LErry.li
+ * Date: 2018-06-17
+ * Time: 14:47
+ */
+@Aspect
+@Component
+public class ServiceLogAspect {
+
+ private final Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);
+
+ /**
+ * 环绕通知方法
+ * @param joinPoint 连接点
+ * @return 切入点返回值
+ * @throws Throwable 异常信息
+ */
+ @Around("@within(com.company.project.common.annotations.ServiceLog) ||@annotation(com.company.project.common.annotations.ServiceLog)")
+ public Object doServiceLog(ProceedingJoinPoint joinPoint) throws Throwable{
+ MethodSignature signature = (MethodSignature) joinPoint.getSignature();
+ // 拦截的实体类
+ Object target = joinPoint.getTarget();
+ // 拦截的方法名称
+ String methodName = signature.getName();
+ // 拦截的放参数类型
+ Class[] parameterTypes = signature.getMethod().getParameterTypes();
+
+ Method method = target.getClass().getMethod(methodName, parameterTypes);
+ if(null == method){
+ return joinPoint.proceed();
+ }
+ // 判断是否包含自定义的注解
+ if (!method.isAnnotationPresent(ServiceLog.class)) {
+ return joinPoint.proceed();
+ }
+ String methodParams = LogAspectUtil.getMethodParams(joinPoint);
+ logger.info("开始请求方法:[{}] 参数:[{}]", methodName, methodParams);
+ long start = System.currentTimeMillis();
+ Object result = joinPoint.proceed();
+ long end = System.currentTimeMillis();
+ String deleteSensitiveContent = LogAspectUtil.deleteSensitiveContent(result);
+ logger.info("结束请求方法:[{}] 参数:[{}] 返回结果[{}] 耗时:[{}]毫秒 ",
+ methodName, methodParams, deleteSensitiveContent, end - start);
+ return result;
+ }
+
+ /**
+ * 获取注解中对方法的描述信息 用于service层注解
+ * @param joinPoint
+ * @return
+ */
+ private String getServiceMethodDescription(ProceedingJoinPoint joinPoint){
+ String targetName = joinPoint.getTarget().getClass().getName();
+ String methodName = joinPoint.getSignature().getName();
+ Object[] arguments = joinPoint.getArgs();
+ Class targetClass = null;
+ try {
+ targetClass = Class.forName(targetName);
+ } catch (ClassNotFoundException e) {
+ throw new ClassCastException();
+ }
+ Method[] methods = targetClass.getMethods();
+ String description = "";
+ for(Method method : methods) {
+ if(method.getName().equals(methodName)) {
+ Class[] clazzs = method.getParameterTypes();
+ if(clazzs.length == arguments.length && null != method.getAnnotation(ServiceLog.class)) {
+ description = method.getAnnotation(ServiceLog.class).description();
+ break;
+ }
+ }
+ }
+ return description;
+ }
+
+}
diff --git a/src/main/java/com/company/project/common/exception/BaseGlobalExceptionHandler.java b/src/main/java/com/company/project/common/exception/BaseGlobalExceptionHandler.java
new file mode 100644
index 000000000..c245f890a
--- /dev/null
+++ b/src/main/java/com/company/project/common/exception/BaseGlobalExceptionHandler.java
@@ -0,0 +1,85 @@
+package com.company.project.common.exception;
+
+import com.company.project.common.result.DefaultErrorResult;
+import com.company.project.common.result.ParameterInvalidItem;
+import com.company.project.common.result.ResultCode;
+import com.company.project.common.util.ConvertUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.http.converter.HttpMessageNotReadableException;
+import org.springframework.validation.BindException;
+import org.springframework.web.bind.MethodArgumentNotValidException;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.validation.ConstraintViolationException;
+import java.util.List;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 聚合层全局异常处理类
+ * @author LErry.li
+ * Date: 2018-06-15
+ * Time: 14:40
+ */
+public class BaseGlobalExceptionHandler {
+
+ private Logger log = LoggerFactory.getLogger(this.getClass());
+ /**
+ * 违反约束异常
+ */
+ protected DefaultErrorResult handleConstraintViolationException(ConstraintViolationException e, HttpServletRequest request) {
+ log.info("handleConstraintViolationException start, uri:{}, caused by: ", request.getRequestURI(), e);
+ List parameterInvalidItemList = ConvertUtil.convertCVSetToParameterInvalidItemList(e.getConstraintViolations());
+ return DefaultErrorResult.failure(ResultCode.PARAM_IS_INVALID, e, HttpStatus.BAD_REQUEST, parameterInvalidItemList);
+ }
+
+ /**
+ * 处理验证参数封装错误时异常
+ */
+ protected DefaultErrorResult handleConstraintViolationException(HttpMessageNotReadableException e, HttpServletRequest request) {
+ log.info("handleConstraintViolationException start, uri:{}, caused by: ", request.getRequestURI(), e);
+ return DefaultErrorResult.failure(ResultCode.PARAM_IS_INVALID, e, HttpStatus.BAD_REQUEST);
+ }
+
+ /**
+ * 处理参数绑定时异常(反400错误码)
+ */
+ protected DefaultErrorResult handleBindException(BindException e, HttpServletRequest request) {
+ log.info("handleBindException start, uri:{}, caused by: ", request.getRequestURI(), e);
+ List parameterInvalidItemList = ConvertUtil.convertBindingResultToMapParameterInvalidItemList(e.getBindingResult());
+ return DefaultErrorResult.failure(ResultCode.PARAM_IS_INVALID, e, HttpStatus.BAD_REQUEST, parameterInvalidItemList);
+ }
+
+ /**
+ * 处理使用@Validated注解时,参数验证错误异常(反400错误码)
+ */
+ protected DefaultErrorResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
+ log.info("handleMethodArgumentNotValidException start, uri:{}, caused by: ", request.getRequestURI(), e);
+ List parameterInvalidItemList = ConvertUtil.convertBindingResultToMapParameterInvalidItemList(e.getBindingResult());
+ return DefaultErrorResult.failure(ResultCode.PARAM_IS_INVALID, e, HttpStatus.BAD_REQUEST, parameterInvalidItemList);
+ }
+
+ /**
+ * 处理通用自定义业务异常
+ */
+ protected ResponseEntity handleBusinessException(BusinessException e, HttpServletRequest request) {
+ log.info("handleBusinessException start, uri:{}, exception:{}, caused by: {}", request.getRequestURI(), e.getClass(), e.getMessage());
+
+ DefaultErrorResult defaultErrorResult = DefaultErrorResult.failure(e);
+ return ResponseEntity
+ .status(HttpStatus.valueOf(defaultErrorResult.getStatus()))
+ .body(defaultErrorResult);
+ }
+
+ /**
+ * 处理运行时系统异常(反500错误码)
+ */
+ protected DefaultErrorResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {
+ log.error("handleRuntimeException start, uri:{}, caused by: ", request.getRequestURI(), e);
+ return DefaultErrorResult.failure(ResultCode.SYSTEM_INNER_ERROR, e, HttpStatus.INTERNAL_SERVER_ERROR);
+ }
+
+}
diff --git a/src/main/java/com/company/project/common/exception/BusinessException.java b/src/main/java/com/company/project/common/exception/BusinessException.java
new file mode 100644
index 000000000..7ebfa8399
--- /dev/null
+++ b/src/main/java/com/company/project/common/exception/BusinessException.java
@@ -0,0 +1,60 @@
+package com.company.project.common.exception;
+
+import com.company.project.common.result.ResultCode;
+import lombok.Data;
+import org.springframework.util.StringUtils;
+
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 业务异常类
+ * @author LErry.li
+ * Date: 2018-06-15
+ * Time: 14:41
+ */
+@Data
+public class BusinessException extends RuntimeException {
+
+ private static final long serialVersionUID = 2332608236621015980L;
+
+ protected String code;
+
+ protected String message;
+
+ protected ResultCode resultCode;
+
+ protected Object data;
+
+ public BusinessException() {
+ ExceptionEnum exceptionEnum = ExceptionEnum.getByEClass(this.getClass());
+ if (exceptionEnum != null) {
+ resultCode = exceptionEnum.getResultCode();
+ code = exceptionEnum.getResultCode().code().toString();
+ message = exceptionEnum.getResultCode().message();
+ }
+
+ }
+
+ public BusinessException(String message) {
+ this();
+ this.message = message;
+ }
+
+ public BusinessException(String format, Object... objects) {
+ this();
+ format = StringUtils.replace(format, "{}", "%s");
+ this.message = String.format(format, objects);
+ }
+
+ public BusinessException(ResultCode resultCode, Object data) {
+ this(resultCode);
+ this.data = data;
+ }
+
+ public BusinessException(ResultCode resultCode) {
+ this.resultCode = resultCode;
+ this.code = resultCode.code().toString();
+ this.message = resultCode.message();
+ }
+}
diff --git a/src/main/java/com/company/project/common/exception/DataConflictException.java b/src/main/java/com/company/project/common/exception/DataConflictException.java
new file mode 100644
index 000000000..25f2a34ae
--- /dev/null
+++ b/src/main/java/com/company/project/common/exception/DataConflictException.java
@@ -0,0 +1,41 @@
+package com.company.project.common.exception;
+
+import com.company.project.common.result.ResultCode;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 数据已存在
+ * @author LErry.li
+ * Date: 2018-06-15
+ * Time: 14:41
+ */
+public class DataConflictException extends BusinessException {
+ private static final long serialVersionUID = 3721036867889297081L;
+
+ public DataConflictException() {
+ super();
+ }
+
+ public DataConflictException(Object data) {
+ super();
+ super.data = data;
+ }
+
+ public DataConflictException(ResultCode resultCode) {
+ super(resultCode);
+ }
+
+ public DataConflictException(ResultCode resultCode, Object data) {
+ super(resultCode, data);
+ }
+
+ public DataConflictException(String msg) {
+ super(msg);
+ }
+
+ public DataConflictException(String formatMsg, Object... objects) {
+ super(formatMsg, objects);
+ }
+
+}
diff --git a/src/main/java/com/company/project/common/exception/DataNotFoundException.java b/src/main/java/com/company/project/common/exception/DataNotFoundException.java
new file mode 100644
index 000000000..af2e3319f
--- /dev/null
+++ b/src/main/java/com/company/project/common/exception/DataNotFoundException.java
@@ -0,0 +1,42 @@
+package com.company.project.common.exception;
+
+
+import com.company.project.common.result.ResultCode;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 数据未找到
+ * @author LErry.li
+ * Date: 2018-06-15
+ * Time: 14:41
+ */
+public class DataNotFoundException extends BusinessException {
+ private static final long serialVersionUID = 3721036867889297081L;
+
+ public DataNotFoundException() {
+ super();
+ }
+
+ public DataNotFoundException(Object data) {
+ super();
+ super.data = data;
+ }
+
+ public DataNotFoundException(ResultCode resultCode) {
+ super(resultCode);
+ }
+
+ public DataNotFoundException(ResultCode resultCode, Object data) {
+ super(resultCode, data);
+ }
+
+ public DataNotFoundException(String msg) {
+ super(msg);
+ }
+
+ public DataNotFoundException(String formatMsg, Object... objects) {
+ super(formatMsg, objects);
+ }
+
+}
diff --git a/src/main/java/com/company/project/common/exception/ExceptionEnum.java b/src/main/java/com/company/project/common/exception/ExceptionEnum.java
new file mode 100644
index 000000000..e14bb9ec9
--- /dev/null
+++ b/src/main/java/com/company/project/common/exception/ExceptionEnum.java
@@ -0,0 +1,126 @@
+package com.company.project.common.exception;
+
+import com.company.project.common.result.ResultCode;
+import org.springframework.http.HttpStatus;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 异常、HTTP状态码、默认自定义返回码 映射类
+ * @author LErry.li
+ * Date: 2018-06-15
+ * Time: 14:41
+ */
+public enum ExceptionEnum {
+ /**
+ * 无效参数
+ */
+ PARAMETER_INVALID(ParameterInvalidException.class, HttpStatus.BAD_REQUEST, ResultCode.PARAM_IS_INVALID),
+
+ /**
+ * 数据未找到
+ */
+ NOT_FOUND(DataNotFoundException.class, HttpStatus.NOT_FOUND, ResultCode.RESULE_DATA_NONE),
+
+ /**
+ * 数据已存在
+ */
+ CONFLICT(DataConflictException.class, HttpStatus.CONFLICT, ResultCode.DATA_ALREADY_EXISTED),
+
+ /**
+ * 用户未登录
+ */
+ UNAUTHORIZED(UserNotLoginException.class, HttpStatus.UNAUTHORIZED, ResultCode.USER_NOT_LOGGED_IN),
+
+ /**
+ * 无访问权限
+ */
+ FORBIDDEN(PermissionForbiddenException.class, HttpStatus.FORBIDDEN, ResultCode.PERMISSION_NO_ACCESS),
+
+ /**
+ * 远程访问时错误
+ */
+ REMOTE_ACCESS_ERROR(RemoteAccessException.class, HttpStatus.INTERNAL_SERVER_ERROR, ResultCode.INTERFACE_OUTTER_INVOKE_ERROR),
+
+ /**
+ * 系统内部错误
+ */
+ INTERNAL_SERVER_ERROR(InternalServerException.class, HttpStatus.INTERNAL_SERVER_ERROR, ResultCode.SYSTEM_INNER_ERROR);
+
+ private Class extends BusinessException> eClass;
+
+ private HttpStatus httpStatus;
+
+ private ResultCode resultCode;
+
+ /**
+ * @param eClass
+ * @param httpStatus
+ * @param resultCode
+ */
+ ExceptionEnum(Class extends BusinessException> eClass, HttpStatus httpStatus, ResultCode resultCode) {
+ this.eClass = eClass;
+ this.httpStatus = httpStatus;
+ this.resultCode = resultCode;
+ }
+
+ public Class extends BusinessException> getEClass() {
+ return eClass;
+ }
+
+ public HttpStatus getHttpStatus() {
+ return httpStatus;
+ }
+
+ public ResultCode getResultCode() {
+ return resultCode;
+ }
+
+ public static boolean isSupportHttpStatus(int httpStatus) {
+ for (ExceptionEnum exceptionEnum : ExceptionEnum.values()) {
+ if (exceptionEnum.httpStatus.value() == httpStatus) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ public static boolean isSupportException(Class> z) {
+ for (ExceptionEnum exceptionEnum : ExceptionEnum.values()) {
+ if (exceptionEnum.eClass.equals(z)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ public static ExceptionEnum getByHttpStatus(HttpStatus httpStatus) {
+ if (httpStatus == null) {
+ return null;
+ }
+
+ for (ExceptionEnum exceptionEnum : ExceptionEnum.values()) {
+ if (httpStatus.equals(exceptionEnum.httpStatus)) {
+ return exceptionEnum;
+ }
+ }
+
+ return null;
+ }
+
+ public static ExceptionEnum getByEClass(Class extends BusinessException> eClass) {
+ if (eClass == null) {
+ return null;
+ }
+
+ for (ExceptionEnum exceptionEnum : ExceptionEnum.values()) {
+ if (eClass.equals(exceptionEnum.eClass)) {
+ return exceptionEnum;
+ }
+ }
+
+ return null;
+ }
+}
diff --git a/src/main/java/com/company/project/common/exception/GlobalExceptionHandler.java b/src/main/java/com/company/project/common/exception/GlobalExceptionHandler.java
new file mode 100644
index 000000000..09ab65a3a
--- /dev/null
+++ b/src/main/java/com/company/project/common/exception/GlobalExceptionHandler.java
@@ -0,0 +1,89 @@
+package com.company.project.common.exception;
+
+import com.company.project.common.result.DefaultErrorResult;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.http.converter.HttpMessageNotReadableException;
+import org.springframework.validation.BindException;
+import org.springframework.web.bind.MethodArgumentNotValidException;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseStatus;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.validation.ConstraintViolationException;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 统一异常处理器
+ * @author LErry.li
+ * Date: 2018-06-15
+ * Time: 14:41
+ */
+@RestController
+@ControllerAdvice
+public class GlobalExceptionHandler extends BaseGlobalExceptionHandler {
+
+ /**
+ * 处理400类异常
+ * @param e
+ * @param request
+ * @return
+ */
+ @ResponseStatus(HttpStatus.BAD_REQUEST)
+ @ExceptionHandler(ConstraintViolationException.class)
+ @Override
+ public DefaultErrorResult handleConstraintViolationException(ConstraintViolationException e, HttpServletRequest request) {
+ return super.handleConstraintViolationException(e, request);
+ }
+
+ @ResponseStatus(HttpStatus.BAD_REQUEST)
+ @ExceptionHandler(HttpMessageNotReadableException.class)
+ @Override
+ public DefaultErrorResult handleConstraintViolationException(HttpMessageNotReadableException e, HttpServletRequest request) {
+ return super.handleConstraintViolationException(e, request);
+ }
+
+ @ResponseStatus(HttpStatus.BAD_REQUEST)
+ @ExceptionHandler(BindException.class)
+ @Override
+ public DefaultErrorResult handleBindException(BindException e, HttpServletRequest request) {
+ return super.handleBindException(e, request);
+ }
+
+ @ResponseStatus(HttpStatus.BAD_REQUEST)
+ @ExceptionHandler(MethodArgumentNotValidException.class)
+ @Override
+ public DefaultErrorResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
+ return super.handleMethodArgumentNotValidException(e, request);
+ }
+
+ /**
+ * 处理自定义异常
+ * @param e
+ * @param request
+ * @return
+ */
+ @ExceptionHandler(BusinessException.class)
+ @Override
+ public ResponseEntity handleBusinessException(BusinessException e, HttpServletRequest request) {
+ return super.handleBusinessException(e, request);
+ }
+
+
+ /**
+ * 处理运行时异常
+ * @param e
+ * @param request
+ * @return
+ */
+ @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
+ @ExceptionHandler(RuntimeException.class)
+ @Override
+ public DefaultErrorResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {
+ //TODO 可通过邮件、微信公众号等方式发送信息至开发人员、记录存档等操作
+ return super.handleRuntimeException(e, request);
+ }
+}
diff --git a/src/main/java/com/company/project/common/exception/InternalServerException.java b/src/main/java/com/company/project/common/exception/InternalServerException.java
new file mode 100644
index 000000000..6c072f13a
--- /dev/null
+++ b/src/main/java/com/company/project/common/exception/InternalServerException.java
@@ -0,0 +1,34 @@
+package com.company.project.common.exception;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 系统内部错误
+ * @author LErry.li
+ * Date: 2018-06-15
+ * Time: 14:41
+ */
+public class InternalServerException extends BusinessException {
+ private static final long serialVersionUID = 2659909836556958676L;
+
+ public InternalServerException() {
+ super();
+ }
+
+ public InternalServerException(String msg, Throwable cause) {
+ super(msg, cause);
+ }
+
+ public InternalServerException(String msg, Throwable cause, Object... objects) {
+ super(msg, cause, objects);
+ }
+
+ public InternalServerException(String msg) {
+ super(msg);
+ }
+
+ public InternalServerException(String formatMsg, Object... objects) {
+ super(formatMsg, objects);
+ }
+
+}
diff --git a/src/main/java/com/company/project/common/exception/ParameterInvalidException.java b/src/main/java/com/company/project/common/exception/ParameterInvalidException.java
new file mode 100644
index 000000000..dd4abd523
--- /dev/null
+++ b/src/main/java/com/company/project/common/exception/ParameterInvalidException.java
@@ -0,0 +1,42 @@
+package com.company.project.common.exception;
+
+
+import com.company.project.common.result.ResultCode;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 参数无效异常
+ * @author LErry.li
+ * Date: 2018-06-15
+ * Time: 14:41
+ */
+public class ParameterInvalidException extends BusinessException {
+ private static final long serialVersionUID = 3721036867889297081L;
+
+ public ParameterInvalidException() {
+ super();
+ }
+
+ public ParameterInvalidException(Object data) {
+ super();
+ super.data = data;
+ }
+
+ public ParameterInvalidException(ResultCode resultCode) {
+ super(resultCode);
+ }
+
+ public ParameterInvalidException(ResultCode resultCode, Object data) {
+ super(resultCode, data);
+ }
+
+ public ParameterInvalidException(String msg) {
+ super(msg);
+ }
+
+ public ParameterInvalidException(String formatMsg, Object... objects) {
+ super(formatMsg, objects);
+ }
+
+}
diff --git a/src/main/java/com/company/project/common/exception/PermissionForbiddenException.java b/src/main/java/com/company/project/common/exception/PermissionForbiddenException.java
new file mode 100644
index 000000000..9bc648667
--- /dev/null
+++ b/src/main/java/com/company/project/common/exception/PermissionForbiddenException.java
@@ -0,0 +1,41 @@
+package com.company.project.common.exception;
+
+
+import com.company.project.common.result.ResultCode;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 权限不足异常
+ * @author LErry.li
+ * Date: 2018-06-15
+ * Time: 14:41
+ */
+public class PermissionForbiddenException extends BusinessException {
+ private static final long serialVersionUID = 3721036867889297081L;
+
+ public PermissionForbiddenException() {
+ super();
+ }
+
+ public PermissionForbiddenException(Object data) {
+ super.data = data;
+ }
+
+ public PermissionForbiddenException(ResultCode resultCode) {
+ super(resultCode);
+ }
+
+ public PermissionForbiddenException(ResultCode resultCode, Object data) {
+ super(resultCode, data);
+ }
+
+ public PermissionForbiddenException(String msg) {
+ super(msg);
+ }
+
+ public PermissionForbiddenException(String formatMsg, Object... objects) {
+ super(formatMsg, objects);
+ }
+
+}
diff --git a/src/main/java/com/company/project/common/exception/RemoteAccessException.java b/src/main/java/com/company/project/common/exception/RemoteAccessException.java
new file mode 100644
index 000000000..765902359
--- /dev/null
+++ b/src/main/java/com/company/project/common/exception/RemoteAccessException.java
@@ -0,0 +1,40 @@
+package com.company.project.common.exception;
+
+import com.company.project.common.result.ResultCode;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 远程访问时错误
+ * @author LErry.li
+ * Date: 2018-06-15
+ * Time: 14:41
+ */
+public class RemoteAccessException extends BusinessException {
+ private static final long serialVersionUID = -832464574076215195L;
+
+ public RemoteAccessException() {
+ super();
+ }
+
+ public RemoteAccessException(Object data) {
+ super.data = data;
+ }
+
+ public RemoteAccessException(ResultCode resultCode) {
+ super(resultCode);
+ }
+
+ public RemoteAccessException(ResultCode resultCode, Object data) {
+ super(resultCode, data);
+ }
+
+ public RemoteAccessException(String msg) {
+ super(msg);
+ }
+
+ public RemoteAccessException(String formatMsg, Object... objects) {
+ super(formatMsg, objects);
+ }
+
+}
diff --git a/src/main/java/com/company/project/common/exception/UserNotLoginException.java b/src/main/java/com/company/project/common/exception/UserNotLoginException.java
new file mode 100644
index 000000000..f7572a30d
--- /dev/null
+++ b/src/main/java/com/company/project/common/exception/UserNotLoginException.java
@@ -0,0 +1,26 @@
+package com.company.project.common.exception;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 用户未登录
+ * @author LErry.li
+ * Date: 2018-06-15
+ * Time: 14:41
+ */
+public class UserNotLoginException extends BusinessException {
+ private static final long serialVersionUID = -1879503946782379204L;
+
+ public UserNotLoginException() {
+ super();
+ }
+
+ public UserNotLoginException(String msg) {
+ super(msg);
+ }
+
+ public UserNotLoginException(String formatMsg, Object... objects) {
+ super(formatMsg, objects);
+ }
+
+}
diff --git a/src/main/java/com/company/project/common/exception/package-info.java b/src/main/java/com/company/project/common/exception/package-info.java
new file mode 100644
index 000000000..afff24da2
--- /dev/null
+++ b/src/main/java/com/company/project/common/exception/package-info.java
@@ -0,0 +1,9 @@
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 全局异常处理
+ * @author LErry.li
+ * Date: 2018-06-16
+ * Time: 14:29
+ */
+package com.company.project.common.exception;
\ No newline at end of file
diff --git a/src/main/java/com/company/project/common/interceptor/AllowCrossDomainInterceptor.java b/src/main/java/com/company/project/common/interceptor/AllowCrossDomainInterceptor.java
new file mode 100644
index 000000000..20a536646
--- /dev/null
+++ b/src/main/java/com/company/project/common/interceptor/AllowCrossDomainInterceptor.java
@@ -0,0 +1,52 @@
+package com.company.project.common.interceptor;
+
+import com.company.project.EnvironmentEnum;
+import com.company.project.common.util.StringUtil;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.env.Environment;
+import org.springframework.stereotype.Component;
+import org.springframework.web.servlet.HandlerInterceptor;
+import org.springframework.web.servlet.ModelAndView;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 允许跨域拦截器
+ * @author LErry.li
+ * Date: 2018-06-16
+ * Time: 14:36
+ */
+@Component
+public class AllowCrossDomainInterceptor implements HandlerInterceptor {
+
+ @Autowired
+ private Environment env;
+
+ @Override
+ public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
+ //仅在非正式环境下生效
+ if (!EnvironmentEnum.isProdEnv(env)) {
+ String origin = httpServletRequest.getHeader("Origin");
+ httpServletResponse.setHeader("Access-Control-Allow-Origin", StringUtil.isEmpty(origin) ? "*" : origin);
+ httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH");
+ httpServletResponse.setHeader("Access-Control-Max-Age", "0");
+ httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
+ httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
+ httpServletResponse.setHeader("XDomainRequestAllowed", "1");
+ }
+ return true;
+ }
+
+ @Override
+ public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
+ // nothing to do
+ }
+
+ @Override
+ public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
+ // nothing to do
+ }
+}
diff --git a/src/main/java/com/company/project/common/interceptor/ResponseResultInterceptor.java b/src/main/java/com/company/project/common/interceptor/ResponseResultInterceptor.java
new file mode 100644
index 000000000..aa1c7ff72
--- /dev/null
+++ b/src/main/java/com/company/project/common/interceptor/ResponseResultInterceptor.java
@@ -0,0 +1,52 @@
+package com.company.project.common.interceptor;
+
+import com.company.project.common.result.ResponseResult;
+import org.springframework.stereotype.Component;
+import org.springframework.web.method.HandlerMethod;
+import org.springframework.web.servlet.HandlerInterceptor;
+import org.springframework.web.servlet.ModelAndView;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.lang.reflect.Method;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 接口响应体控制拦截器
+ * @author LErry.li
+ * Date: 2018-06-15
+ * Time: 14:41
+ */
+@Component
+public class ResponseResultInterceptor implements HandlerInterceptor {
+
+ public static final String RESPONSE_RESULT = "RESPONSE-RESULT";
+
+ @Override
+ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
+ if (handler instanceof HandlerMethod) {
+ final HandlerMethod handlerMethod = (HandlerMethod) handler;
+ final Class> clazz = handlerMethod.getBeanType();
+ final Method method = handlerMethod.getMethod();
+ if (clazz.isAnnotationPresent(ResponseResult.class)) {
+ request.setAttribute(RESPONSE_RESULT, clazz.getAnnotation(ResponseResult.class));
+ } else if (method.isAnnotationPresent(ResponseResult.class)) {
+ request.setAttribute(RESPONSE_RESULT, method.getAnnotation(ResponseResult.class));
+ }
+ }
+
+ return true;
+ }
+
+ @Override
+ public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
+ // nothing to do
+ }
+
+ @Override
+ public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
+ // nothing to do
+ }
+
+}
diff --git a/src/main/java/com/company/project/common/interceptor/package-info.java b/src/main/java/com/company/project/common/interceptor/package-info.java
new file mode 100644
index 000000000..1aaade2f1
--- /dev/null
+++ b/src/main/java/com/company/project/common/interceptor/package-info.java
@@ -0,0 +1,9 @@
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 拦截器
+ * @author LErry.li
+ * Date: 2018-06-16
+ * Time: 14:34
+ */
+package com.company.project.common.interceptor;
\ No newline at end of file
diff --git a/src/main/java/com/company/project/common/mapper/CrudMapper.java b/src/main/java/com/company/project/common/mapper/CrudMapper.java
new file mode 100644
index 000000000..f0fd73a9f
--- /dev/null
+++ b/src/main/java/com/company/project/common/mapper/CrudMapper.java
@@ -0,0 +1,16 @@
+package com.company.project.common.mapper;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 基础增删改查功能mapper
+ * @author LErry.li
+ * Date: 2018-06-16
+ * Time: 12:49
+ */
+public interface CrudMapper extends
+ InsertMapper,
+ DeleteMapper,
+ UpdateMapper,
+ SelectMapper {
+}
diff --git a/src/main/java/com/company/project/common/mapper/DeleteMapper.java b/src/main/java/com/company/project/common/mapper/DeleteMapper.java
new file mode 100644
index 000000000..279a8e302
--- /dev/null
+++ b/src/main/java/com/company/project/common/mapper/DeleteMapper.java
@@ -0,0 +1,21 @@
+package com.company.project.common.mapper;
+
+import tk.mybatis.mapper.common.Marker;
+import tk.mybatis.mapper.common.base.delete.DeleteByPrimaryKeyMapper;
+import tk.mybatis.mapper.common.condition.DeleteByConditionMapper;
+import tk.mybatis.mapper.common.ids.DeleteByIdsMapper;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 基础删除功能mapper
+ * @author LErry.li
+ * Date: 2018-06-16
+ * Time: 12:46
+ */
+public interface DeleteMapper extends Marker,
+ tk.mybatis.mapper.common.base.delete.DeleteMapper,
+ DeleteByPrimaryKeyMapper,
+ DeleteByConditionMapper,
+ DeleteByIdsMapper {
+}
diff --git a/src/main/java/com/company/project/common/mapper/InsertMapper.java b/src/main/java/com/company/project/common/mapper/InsertMapper.java
new file mode 100644
index 000000000..dbf13de15
--- /dev/null
+++ b/src/main/java/com/company/project/common/mapper/InsertMapper.java
@@ -0,0 +1,19 @@
+package com.company.project.common.mapper;
+
+import tk.mybatis.mapper.common.Marker;
+import tk.mybatis.mapper.common.MySqlMapper;
+import tk.mybatis.mapper.common.base.insert.InsertSelectiveMapper;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 基础插入功能mapper
+ * @author LErry.li
+ * Date: 2018-06-16
+ * Time: 12:44
+ */
+public interface InsertMapper extends Marker,
+ tk.mybatis.mapper.common.base.insert.InsertMapper,
+ InsertSelectiveMapper,
+ MySqlMapper {
+}
diff --git a/src/main/java/com/company/project/common/mapper/SelectMapper.java b/src/main/java/com/company/project/common/mapper/SelectMapper.java
new file mode 100644
index 000000000..0567fe7fe
--- /dev/null
+++ b/src/main/java/com/company/project/common/mapper/SelectMapper.java
@@ -0,0 +1,29 @@
+package com.company.project.common.mapper;
+
+import tk.mybatis.mapper.common.Marker;
+import tk.mybatis.mapper.common.base.select.*;
+import tk.mybatis.mapper.common.condition.SelectByConditionMapper;
+import tk.mybatis.mapper.common.condition.SelectCountByConditionMapper;
+import tk.mybatis.mapper.common.example.SelectByExampleMapper;
+import tk.mybatis.mapper.common.ids.SelectByIdsMapper;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 基础查询功能mapper
+ * @author LErry.li
+ * Date: 2018-06-16
+ * Time: 12:48
+ */
+public interface SelectMapper extends Marker,
+ SelectOneMapper,
+ tk.mybatis.mapper.common.base.select.SelectMapper,
+ SelectAllMapper,
+ SelectCountMapper,
+ SelectByPrimaryKeyMapper,
+ ExistsWithPrimaryKeyMapper,
+ SelectByIdsMapper,
+ SelectByConditionMapper,
+ SelectCountByConditionMapper,
+ SelectByExampleMapper {
+}
diff --git a/src/main/java/com/company/project/common/mapper/UpdateMapper.java b/src/main/java/com/company/project/common/mapper/UpdateMapper.java
new file mode 100644
index 000000000..e4f66da3e
--- /dev/null
+++ b/src/main/java/com/company/project/common/mapper/UpdateMapper.java
@@ -0,0 +1,24 @@
+package com.company.project.common.mapper;
+
+import tk.mybatis.mapper.common.Marker;
+import tk.mybatis.mapper.common.base.update.UpdateByPrimaryKeyMapper;
+import tk.mybatis.mapper.common.base.update.UpdateByPrimaryKeySelectiveMapper;
+import tk.mybatis.mapper.common.condition.UpdateByConditionMapper;
+import tk.mybatis.mapper.common.condition.UpdateByConditionSelectiveMapper;
+import tk.mybatis.mapper.common.example.UpdateByExampleSelectiveMapper;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 基础更新功能mapper
+ * @author LErry.li
+ * Date: 2018-06-16
+ * Time: 12:47
+ */
+public interface UpdateMapper extends Marker,
+ UpdateByPrimaryKeyMapper,
+ UpdateByPrimaryKeySelectiveMapper,
+ UpdateByConditionMapper,
+ UpdateByConditionSelectiveMapper,
+ UpdateByExampleSelectiveMapper {
+}
diff --git a/src/main/java/com/company/project/common/mapper/package-info.java b/src/main/java/com/company/project/common/mapper/package-info.java
new file mode 100644
index 000000000..b50d2ea5d
--- /dev/null
+++ b/src/main/java/com/company/project/common/mapper/package-info.java
@@ -0,0 +1,9 @@
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 通用Mapper
+ * @author LErry.li
+ * Date: 2018-06-16
+ * Time: 14:29
+ */
+package com.company.project.common.mapper;
\ No newline at end of file
diff --git a/src/main/java/com/company/project/common/result/DefaultErrorResult.java b/src/main/java/com/company/project/common/result/DefaultErrorResult.java
new file mode 100644
index 000000000..e84072d44
--- /dev/null
+++ b/src/main/java/com/company/project/common/result/DefaultErrorResult.java
@@ -0,0 +1,104 @@
+package com.company.project.common.result;
+
+import cn.hutool.core.util.StrUtil;
+import com.company.project.common.exception.BusinessException;
+import com.company.project.common.exception.ExceptionEnum;
+import com.company.project.common.util.RequestContextHolderUtil;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.springframework.http.HttpStatus;
+
+import java.util.Date;
+
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 默认全局错误返回结果
+ * @author LErry.li
+ * Date: 2018-06-15
+ * Time: 14:41
+ */
+@Builder
+@AllArgsConstructor
+@NoArgsConstructor
+@Data
+public class DefaultErrorResult implements Result {
+ private static final long serialVersionUID = 1899083570489722793L;
+
+ /**
+ * HTTP响应状态码 {@link org.springframework.http.HttpStatus}
+ */
+ private Integer status;
+
+ /**
+ * HTTP响应状态码的英文提示
+ */
+ private String error;
+
+ /**
+ * 异常堆栈的精简信息
+ *
+ */
+ private String message;
+
+ /**
+ * 我们系统内部自定义的返回值编码,{@link ResultCode} 它是对错误更加详细的编码
+ *
+ * 备注:spring boot默认返回异常时,该字段为null
+ */
+ private Integer code;
+
+ /**
+ * 调用接口路径
+ */
+ private String path;
+
+ /**
+ * 异常的名字
+ */
+ private String exception;
+
+ /**
+ * 异常的错误传递的数据
+ */
+ private Object errors;
+
+ /**
+ * 时间戳
+ */
+ private Date timestamp;
+
+ public static DefaultErrorResult failure(ResultCode resultCode, Throwable e, HttpStatus httpStatus, Object errors) {
+ DefaultErrorResult result = DefaultErrorResult.failure(resultCode, e, httpStatus);
+ result.setErrors(errors);
+ return result;
+ }
+
+ public static DefaultErrorResult failure(ResultCode resultCode, Throwable e, HttpStatus httpStatus) {
+ DefaultErrorResult result = new DefaultErrorResult();
+ result.setCode(resultCode.code());
+ result.setMessage(resultCode.message());
+ result.setStatus(httpStatus.value());
+ result.setError(httpStatus.getReasonPhrase());
+ result.setException(e.getClass().getName());
+ result.setPath(RequestContextHolderUtil.getRequest().getRequestURI());
+ result.setTimestamp(new Date());
+ return result;
+ }
+
+ public static DefaultErrorResult failure(BusinessException e) {
+ ExceptionEnum ee = ExceptionEnum.getByEClass(e.getClass());
+ if (ee != null) {
+ return DefaultErrorResult.failure(ee.getResultCode(), e, ee.getHttpStatus(), e.getData());
+ }
+
+ DefaultErrorResult defaultErrorResult = DefaultErrorResult.failure(e.getResultCode() == null ? ResultCode.SUCCESS : e.getResultCode(), e, HttpStatus.OK, e.getData());
+ if (StrUtil.isNotEmpty(e.getMessage())) {
+ defaultErrorResult.setMessage(e.getMessage());
+ }
+ return defaultErrorResult;
+ }
+}
diff --git a/src/main/java/com/company/project/common/result/ParameterInvalidItem.java b/src/main/java/com/company/project/common/result/ParameterInvalidItem.java
new file mode 100644
index 000000000..639f69436
--- /dev/null
+++ b/src/main/java/com/company/project/common/result/ParameterInvalidItem.java
@@ -0,0 +1,34 @@
+package com.company.project.common.result;
+
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 参数无效项
+ * @author LErry.li
+ * Date: 2018-06-15
+ * Time: 14:41
+ */
+@Builder
+@AllArgsConstructor
+@NoArgsConstructor
+@Data
+public class ParameterInvalidItem {
+
+ /**
+ * 无效字段的名称
+ */
+ private String fieldName;
+
+ /**
+ * 错误信息
+ */
+ private String message;
+
+
+}
\ No newline at end of file
diff --git a/src/main/java/com/company/project/common/result/PlatformResult.java b/src/main/java/com/company/project/common/result/PlatformResult.java
new file mode 100644
index 000000000..edcf7e4ce
--- /dev/null
+++ b/src/main/java/com/company/project/common/result/PlatformResult.java
@@ -0,0 +1,83 @@
+package com.company.project.common.result;
+
+
+import com.alibaba.fastjson.JSON;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 平台通用返回结果
+ * @author LErry.li
+ * Date: 2018-06-15
+ * Time: 14:41
+ */
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+@Data
+public class PlatformResult implements Result {
+ private static final long serialVersionUID = 874200365941306385L;
+
+ private Integer code;
+
+ private String message;
+
+ private Object data;
+
+ public PlatformResult setCode(Integer code) {
+ this.code = code;
+ return this;
+ }
+
+ public PlatformResult setMessage(String message) {
+ this.message = message;
+ return this;
+ }
+
+ public static PlatformResult success() {
+ PlatformResult result = new PlatformResult();
+ result.setResultCode(ResultCode.SUCCESS);
+ return result;
+ }
+
+ public static PlatformResult success(Object data) {
+ PlatformResult result = new PlatformResult();
+ result.setResultCode(ResultCode.SUCCESS);
+ result.setData(data);
+ return result;
+ }
+
+ public static PlatformResult failure(ResultCode resultCode) {
+ PlatformResult result = new PlatformResult();
+ result.setResultCode(resultCode);
+ return result;
+ }
+
+ public static PlatformResult failure(ResultCode resultCode, Object data) {
+ PlatformResult result = new PlatformResult();
+ result.setResultCode(resultCode);
+ result.setData(data);
+ return result;
+ }
+
+ public static PlatformResult failure(String message) {
+ PlatformResult result = new PlatformResult();
+ result.setCode(ResultCode.PARAM_IS_INVALID.code());
+ result.setMessage(message);
+ return result;
+ }
+
+ private void setResultCode(ResultCode code) {
+ this.code = code.code();
+ this.message = code.message();
+ }
+
+ @Override
+ public String toString() {
+ return JSON.toJSONString(this);
+ }
+}
diff --git a/src/main/java/com/company/project/common/result/ResponseResult.java b/src/main/java/com/company/project/common/result/ResponseResult.java
new file mode 100644
index 000000000..75ebcd5ad
--- /dev/null
+++ b/src/main/java/com/company/project/common/result/ResponseResult.java
@@ -0,0 +1,18 @@
+package com.company.project.common.result;
+
+import java.lang.annotation.*;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ * 接口返回结果增强 会通过拦截器拦截后放入标记,在WebResponseBodyHandler进行结果处理
+ * @author LErry.li
+ * Date: 2018-06-15
+ * Time: 14:41
+ */
+@Target({ ElementType.TYPE, ElementType.METHOD })
+@Retention(RetentionPolicy.RUNTIME)
+@Documented
+public @interface ResponseResult {
+ Class extends Result> value() default PlatformResult.class;
+}
diff --git a/src/main/java/com/company/project/common/result/ResponseResultHandler.java b/src/main/java/com/company/project/common/result/ResponseResultHandler.java
new file mode 100644
index 000000000..4da1c323b
--- /dev/null
+++ b/src/main/java/com/company/project/common/result/ResponseResultHandler.java
@@ -0,0 +1,50 @@
+package com.company.project.common.result;
+
+import com.company.project.common.interceptor.ResponseResultInterceptor;
+import com.company.project.common.util.RequestContextHolderUtil;
+import org.springframework.core.MethodParameter;
+import org.springframework.http.MediaType;
+import org.springframework.http.converter.HttpMessageConverter;
+import org.springframework.http.server.ServerHttpRequest;
+import org.springframework.http.server.ServerHttpResponse;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
+
+/**
+ * Created with IntelliJ IDEA.
+ * Description:
+ *
+ * @author LErry.li
+ * Date: 2018-06-15
+ * Time: 14:41
+ */
+@ControllerAdvice
+public class ResponseResultHandler implements ResponseBodyAdvice