当前位置:网站首页>Realize automatic logging
Realize automatic logging
2022-07-19 13:12:00 【Programmer seven seven】
I'm using springboot+mybatis-plus Realize automatic logging
Imported xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zwl</groupId>
<artifactId>materiallog</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>materiallog</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.7.RELEASE</spring-boot.version>
</properties>
<!-- <parent>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-parent</artifactId>-->
<!-- <version>2.7.0</version>-->
<!-- <relativePath/>-->
<!-- </parent>-->
<dependencies>
<!--aop-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<!-- Interceptor -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.3.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.7.RELEASE</version>
<configuration>
<mainClass>com.zwl.MateriallogApplication</mainClass>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
yml To configure
server:
port: 8888
file:
path: D:/Development/Excel
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver # I use it mysql5 Of
url: jdbc:mysql://localhost:3306/books?serverTimezone=GMT&useUnicode=true&characterEncoding=utf-8
username: root
password: root
mybatis-plus:
# mybatis Related configuration
mapper-locations: classpath:mapper/*.xml
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
type-aliases-package: com.zwl.entity
Method 1 :Aop Realization
Database table
Log table
CREATE TABLE `device_log` (
`id` int(11) NOT NULL COMMENT 'id',
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ' Operator ',
`uid` int(11) NULL DEFAULT NULL COMMENT ' user id',
`type` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ' Operation type ',
`error` varchar(5000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ' Reasons for failure ',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
User table
CREATE TABLE `user` (
`id` int(255) NOT NULL AUTO_INCREMENT COMMENT ' Primary key Id, At the same time, it can be used for job card number ',
`name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ' full name ',
`password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ' password ',
`phone` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ' contact number ',
`state` varchar(5) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ' Whether it has been disabled ',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2037460995 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = COMPACT;
Create entity class
DeviceLog
import com.baomidou.mybatisplus.annotation.*;
import com.zwl.emuns.OperationType;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName(value = "device_log", autoResultMap = true)
public class DeviceLog implements Serializable {
private static final long serialVersionUID = 1L;
/** * id */
private Integer id;
/** * Operator */
private OperationType name;
/** * user id */
private Integer uid;
/** * Operation type */
private String type;
/** * Reasons for failure */
private String error;
public DeviceLog() {
}
public DeviceLog(Integer id, String type) {
this.id = id;
this.type = type;
}
}
user
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class User implements Serializable {
private static final long serialVersionUID = 5846464524840272868L;
/** * Primary key id */
private Integer id;
/** * full name */
private String name;
/** * password */
private String password;
/** * cell-phone number */
private String phone;
/** * state */
private String state;
}
Create custom annotations
import com.zwl.emuns.OperationType;
import java.lang.annotation.*;
@Target({
ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotation {
String module();
/** Operation type * @return*/
OperationType type();
}
Create annotation return layer
public enum OperationType {
ADD,
UPDATE,
DELETE,
Upload,
Download,
selectAll;
public String getType() {
if (this.equals(ADD)) {
return "ADD";
}
if (this.equals(UPDATE)) {
return "UPDATE";
}
if (this.equals(DELETE)) {
return "DELETE";
}
if (this.equals(Upload)) {
return "Upload";
}
if (this.equals(Download)) {
return "Download";
}if (this.equals(selectAll)) {
return "selectAll";
}
return null;
};
}
public class LogsConstant {
/** * User management */
public static final String BASICS_CURRENCY_USER = " User management -";
public static final String USER_ADD = BASICS_CURRENCY_ROLE + " New role ";
public static final String USER_UPDATE = BASICS_CURRENCY_ROLE + " Edit role ";
public static final String USER_DELETE = BASICS_CURRENCY_ROLE + " Delete the role ";
public static final String USER_SELECT = BASICS_CURRENCY_ROLE + " View role details ";
}
establish Aop section
import com.zwl.annotation.LogAnnotation;
import com.zwl.entity.DeviceLog;
import com.zwl.sevice.DeviceLogService;
import lombok.AllArgsConstructor;
import lombok.Singular;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.security.SecurityUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
@Aspect
@Component
@Slf4j
@AllArgsConstructor
public class LogAspect {
private DeviceLogService deviceLogService;
/** * Defining entry points */
@Pointcut("@annotation(com.zwl.annotation.LogAnnotation)")
public void pt(){
}
/** * Surrounding the notification */
@Around("pt()")
public Object log(ProceedingJoinPoint joinPoint) throws Throwable{
/** * Defining time */
Long beginTime =System.currentTimeMillis();
MethodSignature signature= (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
DeviceLog deviceLog = new DeviceLog();
deviceLog.setType(annotation.module());
deviceLog.setName(annotation.type());
try {
return joinPoint.proceed();
} catch (Exception e) {
log.error(e.getMessage());
deviceLog.setError(e.getMessage());
throw e;
} finally {
deviceLogService.addLog(deviceLog);
}
}
}
Controller layer
UserController
import com.zwl.entity.User;
import com.zwl.response.Result;
import com.zwl.sevice.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
// By way of annotation
@RequestMapping("/add")
@LogAnnotation(module = LogsConstant.USER_ADD,type = OperationType.ADD)
public Result addTest(User user){
return userService.addUser(user);
}
@RequestMapping("/update")
@LogAnnotation(module = LogsConstant.USER_UPDATE,type = OperationType.UPDATE)
public Result updateTest(User user){
return userService.updateUser(user);
}
@RequestMapping("/del")
@LogAnnotation(module = LogsConstant.USER_DELETE,type = OperationType.DELETE)
public Result deleteTest(Integer id){
return userService.deleteUser(id);
}
}
DeviceLogController
import com.zwl.response.Result;
import com.zwl.sevice.DeviceLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/log")
public class DeviceLogController {
@Autowired
private DeviceLogService deviceLogService;
@RequestMapping("/selectAll")
public Result selectAll(){
return deviceLogService.selectAll();
}
}
Return layer
ResultCode
package com.zwl.emuns;
/** * @author zhouleibin * @Type com.sunyard.am.result * @Desc * @date 2021/6/30 8:19 */
public enum ResultCode {
//2xx- success
SUCCESS(200, " Successful operation "),
private Integer code;
private String msg;
ResultCode(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public static ResultCode getEnum(Integer code) {
for (ResultCode retEnum : ResultCode.values()) {
if (retEnum.getCode().equals(code)) {
return retEnum;
}
}
return null;
}
public String getMsg() {
return msg;
}
public Integer getCode() {
return code;
}
}
Result
package com.zwl.response;
import com.zwl.emuns.ResultCode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/** * @author zhouleibin * @Type com.sunyard.am.result * @Desc * @date 2021/6/30 8:17 */
public class Result<T> implements Serializable {
private Integer code;
private String msg;
private T data;
/***/
public static <T> Result<T> create() {
Result<T> result = new Result<>();
result.setData(null);
result.setMsg(ResultCode.SUCCESS.getMsg());
result.setCode(ResultCode.SUCCESS.getCode());
return result;
}
/***/
public static <T> Result<T> create(T value) {
Result<T> result = new Result<>();
result.setData(value);
result.setMsg(ResultCode.SUCCESS.getMsg());
result.setCode(ResultCode.SUCCESS.getCode());
return result;
}
/***/
public static <T> Result<T> error(ResultCode resultCode) {
Result<T> result = new Result<>();
result.setData(null);
result.setMsg(resultCode.getMsg());
result.setCode(resultCode.getCode());
return result;
}
/***/
public static <T> Result<T> error(String message, ResultCode resultCode) {
Result<T> result = new Result<>();
result.setData(null);
if (null == message || 0 == message.length()) {
result.setMsg(resultCode.getMsg());
} else {
result.setMsg(message);
}
result.setCode(resultCode.getCode());
return result;
}
/** * Create a custom callback message * * @param code Receipt code * @param msg Receipt information * @param <T> data type * @return example */
public static <T> Result<T> error(String msg, Integer code) {
Result<T> result = new Result<>();
result.setData(null);
result.setMsg(msg);
result.setCode(code);
return result;
}
/***/
public boolean isSucc() {
return ResultCode.SUCCESS.getCode().equals(this.code);
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
service layer
DeviceLogService:
import com.zwl.entity.DeviceLog;
public interface DeviceLogService {
void addLog(DeviceLog deviceLog);
void selectAll();
}
userService:
import com.zwl.entity.User;
public interface UserService {
void addUser(User user);
void updateUser(User user);
void deleteUser(Integer i);
}
serviceImpl layer
DeviceLogServiceImpl
import com.zwl.response.Result;
import com.zwl.sevice.DeviceLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/** * Revision history * ------------------------------------------------------------------------- * * Date Author Note * ------------------------------------------------------------------------- * creat */
@RestController
@RequestMapping("/log")
public class DeviceLogController {
@Autowired
private DeviceLogService deviceLogService;
@RequestMapping("/selectAll")
public Result selectAll(){
return deviceLogService.selectAll();
}
}
UserServiceImpl
package com.zwl.sevice.Impl;
import com.zwl.entity.DeviceLog;
import com.zwl.entity.User;
import com.zwl.mapper.UserMapper;
import com.zwl.response.Result;
import com.zwl.sevice.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
@Override
@Transactional(rollbackFor = Exception.class)
public Result addUser(User user) {
userMapper.insert(user);
DeviceLog deviceLog = new DeviceLog( null, " New users ");
applicationEventPublisher.publishEvent(deviceLog);
return Result.create();
}
@Override
@Transactional(rollbackFor = Exception.class)
public Result updateUser(User user) {
userMapper.updateById(user);
DeviceLog deviceLog = new DeviceLog(null, " Edit user ");
applicationEventPublisher.publishEvent(deviceLog);
return Result.create();
}
@Override
@Transactional(rollbackFor = Exception.class)
public Result deleteUser(Integer i) {
userMapper.deleteById(i);
DeviceLog deviceLog = new DeviceLog(null, " Delete user ");
applicationEventPublisher.publishEvent(deviceLog);
return Result.create();
}
}
Mapper layer
DeviceLogMapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zwl.entity.DeviceLog;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface DeviceLogMapper extends BaseMapper<DeviceLog> {
}
UserMapper
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
Method 2 : Interceptor implementation
Database table
Log table
CREATE TABLE `device_log` (
`id` int(11) NOT NULL COMMENT 'id',
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ' Operator ',
`uid` int(11) NULL DEFAULT NULL COMMENT ' user id',
`type` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ' Operation type ',
`error` varchar(5000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ' Reasons for failure ',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
User table
CREATE TABLE `user` (
`id` int(255) NOT NULL AUTO_INCREMENT COMMENT ' Primary key Id, At the same time, it can be used for job card number ',
`name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ' full name ',
`password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ' password ',
`phone` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ' contact number ',
`state` varchar(5) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ' Whether it has been disabled ',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2037460995 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = COMPACT;
Create entity class
DeviceLog
import com.baomidou.mybatisplus.annotation.*;
import com.zwl.emuns.OperationType;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName(value = "device_log", autoResultMap = true)
public class DeviceLog implements Serializable {
private static final long serialVersionUID = 1L;
/** * id */
private Integer id;
/** * Operator */
private String name;
/** * user id */
private Integer uid;
/** * Operation type */
private String type;
/** * Reasons for failure */
private String error;
}
user
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class User implements Serializable {
private static final long serialVersionUID = 5846464524840272868L;
/** * Primary key id */
private Integer id;
/** * full name */
private String name;
/** * password */
private String password;
/** * cell-phone number */
private String phone;
/** * state */
private String state;
}
Controller layer
UserController
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zwl.emuns.ResponseCode;
import com.zwl.entity.DeviceLog;
import com.zwl.entity.User;
import com.zwl.response.Result;
import com.zwl.sevice.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.security.KeyStore;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
// By way of annotation
@RequestMapping("/add")
public Result addTest(User user){
userService.addUser(user);
return new Result(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMsg(), " User added successfully ");
}
@RequestMapping("/update")
public Result updateTest(User user){
userService.updateUser(user);
return new Result(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMsg(), " User edited successfully ");
}
@RequestMapping("/del")
public Result deleteTest(Integer id){
userService.deleteUser(id);
return new Result(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMsg(), " User delete successful ");
}
}
DeviceLogController
import com.zwl.annotation.LogAnnotation;
import com.zwl.constant.LogsConstant;
import com.zwl.emuns.OperationType;
import com.zwl.emuns.ResponseCode;
import com.zwl.entity.Account;
import com.zwl.response.Result;
import com.zwl.sevice.DeviceLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/log")
public class DeviceLogController {
@Autowired
private DeviceLogService deviceLogService;
@RequestMapping("/selectAll")
@LogAnnotation(module = LogsConstant.Log_selectAll,type = OperationType.selectAll)
public Result selectAll(){
deviceLogService.selectAll();
return new Result(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMsg(), " Log acquisition succeeded ");
}
}
Return layer
ResultCode
package com.zwl.emuns;
/** * @author zhouleibin * @Type com.sunyard.am.result * @Desc * @date 2021/6/30 8:19 */
public enum ResultCode {
//2xx- success
SUCCESS(200, " Successful operation "),
private Integer code;
private String msg;
ResultCode(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public static ResultCode getEnum(Integer code) {
for (ResultCode retEnum : ResultCode.values()) {
if (retEnum.getCode().equals(code)) {
return retEnum;
}
}
return null;
}
public String getMsg() {
return msg;
}
public Integer getCode() {
return code;
}
}
Result
package com.zwl.response;
import com.zwl.emuns.ResultCode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/** * @author zhouleibin * @Type com.sunyard.am.result * @Desc * @date 2021/6/30 8:17 */
public class Result<T> implements Serializable {
private Integer code;
private String msg;
private T data;
/***/
public static <T> Result<T> create() {
Result<T> result = new Result<>();
result.setData(null);
result.setMsg(ResultCode.SUCCESS.getMsg());
result.setCode(ResultCode.SUCCESS.getCode());
return result;
}
/***/
public static <T> Result<T> create(T value) {
Result<T> result = new Result<>();
result.setData(value);
result.setMsg(ResultCode.SUCCESS.getMsg());
result.setCode(ResultCode.SUCCESS.getCode());
return result;
}
/***/
public static <T> Result<T> error(ResultCode resultCode) {
Result<T> result = new Result<>();
result.setData(null);
result.setMsg(resultCode.getMsg());
result.setCode(resultCode.getCode());
return result;
}
/***/
public static <T> Result<T> error(String message, ResultCode resultCode) {
Result<T> result = new Result<>();
result.setData(null);
if (null == message || 0 == message.length()) {
result.setMsg(resultCode.getMsg());
} else {
result.setMsg(message);
}
result.setCode(resultCode.getCode());
return result;
}
/** * Create a custom callback message * * @param code Receipt code * @param msg Receipt information * @param <T> data type * @return example */
public static <T> Result<T> error(String msg, Integer code) {
Result<T> result = new Result<>();
result.setData(null);
result.setMsg(msg);
result.setCode(code);
return result;
}
/***/
public boolean isSucc() {
return ResultCode.SUCCESS.getCode().equals(this.code);
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
Interceptor
@Component
public class DeviceLogEventListener {
@Autowired
private DeviceLogService deviceLogService;
/** * Log monitoring * @param deviceLog */
@Async
@EventListener(value = DeviceLog.class)
public void saveLog(DeviceLog deviceLog) {
deviceLogService.addLog(deviceLog);
}
}
service layer
DeviceLogService:
import com.zwl.entity.DeviceLog;
public interface DeviceLogService {
void addLog(DeviceLog deviceLog);
void selectAll();
}
userService:
import com.zwl.entity.User;
public interface UserService {
void addUser(User user);
void updateUser(User user);
void deleteUser(Integer i);
}
serviceImpl layer
DeviceLogServiceImpl
import com.zwl.response.Result;
import com.zwl.sevice.DeviceLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/** * Revision history * ------------------------------------------------------------------------- * * Date Author Note * ------------------------------------------------------------------------- * creat */
@RestController
@RequestMapping("/log")
public class DeviceLogController {
@Autowired
private DeviceLogService deviceLogService;
@RequestMapping("/selectAll")
public Result selectAll(){
return deviceLogService.selectAll();
}
}
UserServiceImpl
package com.zwl.sevice.Impl;
import com.zwl.entity.DeviceLog;
import com.zwl.entity.User;
import com.zwl.mapper.UserMapper;
import com.zwl.response.Result;
import com.zwl.sevice.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
@Override
@Transactional(rollbackFor = Exception.class)
public Result addUser(User user) {
userMapper.insert(user);
DeviceLog deviceLog = new DeviceLog( null, " New users ");
applicationEventPublisher.publishEvent(deviceLog);
return Result.create();
}
@Override
@Transactional(rollbackFor = Exception.class)
public Result updateUser(User user) {
userMapper.updateById(user);
DeviceLog deviceLog = new DeviceLog(null, " Edit user ");
applicationEventPublisher.publishEvent(deviceLog);
return Result.create();
}
@Override
@Transactional(rollbackFor = Exception.class)
public Result deleteUser(Integer i) {
userMapper.deleteById(i);
DeviceLog deviceLog = new DeviceLog(null, " Delete user ");
applicationEventPublisher.publishEvent(deviceLog);
return Result.create();
}
}
Mapper layer
DeviceLogMapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zwl.entity.DeviceLog;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface DeviceLogMapper extends BaseMapper<DeviceLog> {
}
UserMapper
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
边栏推荐
- Uio-66 - (COOH) 2 modified polyamide nanofiltration membrane | zif-8/pvp composite nanofiber membrane | uio-66-nh2 modified polyamide nanofiltration membrane
- A general memory management driver code is sorted out
- Li Kou 413 division of equal difference sequence dynamic programming
- 使用case语句时会产生锁存器的情况
- 2022年最新吉林建筑安全员模拟题库及答案
- 力扣198-213 打家劫舍Ⅰ、Ⅱ——动态规划
- 【Pygame 学习笔记】5.rect对象的碰撞检测
- Three minutes to understand the primary key, foreign key, non empty, unique and default constraints in mysql, and how to create a table
- O & M LITTLE WHITE Growth record - architecture week 6
- 每周小结(*65):有计划的输出
猜你喜欢

Will the market halve? What investment opportunities are there? 2020-03-11

Chitosan coated pcn224 nanoparticles | metal organic skeleton fe-mil-88nh2 | nickel based MOF material (Ni MOF / NF)

sqli-labs(less-11)
[email protected] Support) | uio-66/coso composite | zif-67 nanocrystalline sur"/>Copper sulfide nanoparticles /zif-8 Composites( [email protected] Support) | uio-66/coso composite | zif-67 nanocrystalline sur

Using the case statement will produce a latch condition

JVM self study summary

稳超胜算,历9弥新 | 2022金仓创新产品发布会顺利召开
[email protected] )|Rhodamine 6G modified MOF material | catalase @zif composite | MOF"/>Lanthanide metal organic skeleton( [email protected] )|Rhodamine 6G modified MOF material | catalase @zif composite | MOF

10 minutes to customize the pedestrian analysis system, detection and tracking, behavior recognition, human attributes all in one!

ASP. Net collaborative OA office service management platform source code
随机推荐
LeetCode 0117. 填充每个节点的下一个右侧节点指针 II
整理了一份通用的内存管理驱动代码
实现自动记录日志
Panasonic A6 servo driver external absolute value grating ruler full closed loop parameter setting
運維小白成長記—架構第6周
jvm自学总结
A general memory management driver code is sorted out
Using the case statement will produce a latch condition
RingBuffer
[Yugong series] July 2022 go teaching course 012 forced type conversion
Is it safe for Everbright futures to open an account online? Are there any account opening guidelines?
[pyGame learning notes] 7 event
【错误记录/selectpicker】dropdown menu显示位置出现偏移
大气非等晕效应
LeetCode 0117. Populate the next right node pointer II of each node
Porphyrin encapsulated organometallic frame materials [email protected] |
Return to risk ratio: the most important indicator of investment opportunities 2020-03-14
How to invest scientifically and rationally when the global financial crisis strikes? 2020-03-17
Wrong again, byte alignment and the use of pragma pack
AE如何制作星云粒子特效