Java教程

JAVA项目总结01

本文主要是介绍JAVA项目总结01,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.spring多环境配置

在日常项目开发中,我们通常在配置文件中配置多个运行环境:

  • application.yml
  • application-dev.yml
  • application-prod.yml

那么在运行时,怎么指定运行的配置文件呢?

可以在运行时,通过参数传递来改变运行的环境,前提需要明白,JAVA在加载配置文件时,加载的是application.yml文件,所以,针对于公共的配置信息可以在这个文件配置。

java jar 包运行可以通过传参,来指定配置值,所以我们修改一下application.yml 来接收传参:


 
  1. # 默认使用配置
  2. spring:
  3. profiles:
  4. active: ${spring.profiles.active}

然后在通过运行jar 包的方式来启动项目(需要用maven 打包):在运行时,决定用哪个配置文件通过


 
  1. --spring.profiles.active=dev

指定。


 
  1. java -jar certification-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev

2.MyBatisPlus 分页插件

只需要在项目中配置


 
  1. @Configuration
  2. public class MyBatisPlusConfig {
  3. @Bean
  4. public PaginationInterceptor paginationInterceptor() {
  5. return new PaginationInterceptor();
  6. }
  7. }

使用,直接在需要分页的地方传入IPage参数:


 
  1. IPage<XX> queryByPage(IPage<XX> iPage, @Param("state") int state);

该方法执行完成后,查询数据会存储到 iPage 参数中,可以直接获取方法返回值。值得注意的是,这个方法必须有返回值。

3.springAop实现打印日志注解


 
  1. package org.simulation;
  2.  
  3. import java.lang.annotation.*;
  4.  
  5. /**
  6. <!-- aop 依赖 -->
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-aop</artifactId>
  10. </dependency>
  11.  
  12. <!-- 用于日志切面中,以 json 格式打印出入参 -->
  13. <dependency>
  14. <groupId>com.google.code.gson</groupId>
  15. <artifactId>gson</artifactId>
  16. <version>2.8.5</version>
  17. </dependency>
  18. */
  19. @Retention(RetentionPolicy.RUNTIME)
  20. @Target({ElementType.METHOD})
  21. @Documented
  22. public @interface WebLog {
  23. /**
  24. * 日志描述信息
  25. */
  26. String description() default "";
  27.  
  28. }

 
  1. package org.simulation;
  2.  
  3. import com.google.gson.Gson;
  4. import org.aspectj.lang.JoinPoint;
  5. import org.aspectj.lang.ProceedingJoinPoint;
  6. import org.aspectj.lang.annotation.*;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import org.springframework.context.annotation.Profile;
  10. import org.springframework.stereotype.Component;
  11. import org.springframework.web.context.request.RequestContextHolder;
  12. import org.springframework.web.context.request.ServletRequestAttributes;
  13.  
  14. import javax.servlet.http.HttpServletRequest;
  15. import java.lang.reflect.Method;
  16.  
  17.  
  18. @Aspect
  19. @Component
  20. @Profile({"dev", "test"})
  21. public class WebLogAspect {
  22.  
  23. private final static Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
  24. /**
  25. * 换行符
  26. */
  27. private static final String LINE_SEParaTOR = System.lineseparator();
  28.  
  29. /**
  30. * 以自定义 @WebLog 注解为切点
  31. */
  32. @pointcut("@annotation(org.simulation.WebLog)")
  33. public void webLog() {
  34. }
  35.  
  36. /**
  37. * 在切点之前织入
  38. *
  39. * @param joinPoint
  40. * @throws Throwable
  41. */
  42. @Before("webLog()")
  43. public void dobefore(JoinPoint joinPoint) throws Throwable {
  44. // 开始打印请求日志
  45. ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  46. HttpServletRequest request = attributes.getRequest();
  47.  
  48. // 获取 @WebLog 注解的描述信息
  49. String methodDescription = getAspectLogDescription(joinPoint);
  50.  
  51. // 打印请求相关参数
  52. logger.info("========================================== Start ==========================================");
  53. // 打印请求 url
  54. logger.info("URL : {}", request.getRequestURL().toString());
  55. // 打印描述信息
  56. logger.info("Description : {}", methodDescription);
  57. // 打印 Http method
  58. logger.info("HTTP Method : {}", request.getmethod());
  59. // 打印调用 controller 的全路径以及执行方法
  60. logger.info("Class Method : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
  61. // 打印请求的 IP
  62. logger.info("IP : {}", request.getRemoteAddr());
  63. // 打印请求入参
  64. logger.info("Request Args : {}", new Gson().toJson(joinPoint.getArgs()));
  65. }
  66.  
  67. /**
  68. * 在切点之后织入
  69. */
  70. @After("webLog()")
  71. public void doAfter() throws Throwable {
  72. // 接口结束后换行,方便分割查看
  73. logger.info("=========================================== End ===========================================" + LINE_SEParaTOR);
  74. }
  75.  
  76. /**
  77. * 环绕
  78. */
  79. @Around("webLog()")
  80. public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
  81. long startTime = System.currentTimeMillis();
  82. Object result = proceedingJoinPoint.proceed();
  83. // 打印出参
  84. logger.info("Response Args : {}", new Gson().toJson(result));
  85. // 执行耗时
  86. logger.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
  87. return result;
  88. }
  89.  
  90.  
  91. /**
  92. * 获取切面注解的描述
  93. *
  94. * @param joinPoint 切点
  95. * @return 描述信息
  96. * @throws Exception
  97. */
  98. public String getAspectLogDescription(JoinPoint joinPoint)
  99. throws Exception {
  100. String targetName = joinPoint.getTarget().getClass().getName();
  101. String methodName = joinPoint.getSignature().getName();
  102. Object[] arguments = joinPoint.getArgs();
  103. Class targetClass = Class.forName(targetName);
  104. Method[] methods = targetClass.getmethods();
  105. StringBuilder description = new StringBuilder("");
  106. for (Method method : methods) {
  107. if (method.getName().equals(methodName)) {
  108. Class<?>[] clazzs = method.getParameterTypes();
  109. if (clazzs.length == arguments.length) {
  110. description.append(method.getAnnotation(WebLog.class).description());
  111. break;
  112. }
  113. }
  114. }
  115. return description.toString();
  116. }
  117. }
这篇关于JAVA项目总结01的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!