SpringBoot 经验书

目录

正文

SpringBoot + Mybatis 日志中打印SQL语句

第一种

在 YML 文件中配置日志级别

logging:
  level:
    xin.nick.admin.dao: DEBUG  # xin.nick.admin.dao 我的mapper(dao层)包,改成你自己的

第二种

在 YML 文件中配置 MyBatis 日志打印类, log-impl 实现了打印log日志的某个实现类

mybatis:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

SpringBoot 配置端口

server:
  #端口号
  port: 81

IDEA中设置 SpringBoot 热启动

首先在pom文件中添加引用

<!-- 放在 <dependencies> 元素里面 -->
<!-- 热部署模块 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
     <optional>true</optional> <!-- 这个需要为 true 热部署才有效 -->
</dependency>

再配置构建参数

<!-- 放在<build> 元素里面 -->
<plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
            <fork>true</fork>
        </configuration>
    </plugin>
</plugins>

SpringBoot 默认的静态目录

SpringBoot 默认给我们配置了静态目录

/META-INF/resources/
/resources/
/static/
/public/

优先级:
/META-INF/resources/>/resources/>/static/>/public/

编写从容器中取对象的工具类

@Component
public class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
 
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtil.applicationContext = applicationContext;
    }
 
    public ApplicationContext getApplicationContext(){
        return applicationContext;
    }
 
    public static Object getBean(String beanName){
        return applicationContext.getBean(beanName);
    }
 
    public static <T> T getBean(Class<T> clazz){
        return (T)applicationContext.getBean(clazz);
    }
}

Spring Boot 配置拦截器

先准备拦截器实现类

// GlobalInterceptor.java
@Component
public class GlobalInterceptor implements HandlerInterceptor {

    Logger logger = LoggerFactory.getLogger(GlobalInterceptor.class);

    /**
     * 预处理回调方法,实现处理器的预处理
     * 返回值:true表示继续流程;false表示流程中断,不会继续调用其他的拦截器或处理器
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        logger.info("开始截获请求:" + request.getRequestURI());
        return true;
    }

    /**
     * 后处理回调方法,实现处理器(controller)的后处理,但在渲染视图之前
     * 此时我们可以通过modelAndView对模型数据进行处理或对视图进行处理
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        logger.info(request.getRequestURI() + "请求处理完毕");
    }
    /**
     * 整个请求处理完毕回调方法,即在视图渲染完毕时回调,
     * 如性能监控中我们可以在此记录结束时间并输出消耗时间,
     * 还可以进行一些资源清理,类似于try-catch-finally中的finally,
     * 但仅调用处理器执行链中
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }
}

然后编写配置类,将过滤器配置进去

// MvcInterceptorConfig.java
@Configuration
public class MvcInterceptorConfig extends WebMvcConfigurationSupport {

    @Autowired
    private GlobalInterceptor globalInterceptor;

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        // 多个拦截器组成一个拦截器链
        // addPathPatterns 用于添加拦截规则,/**表示拦截所有请求
        // excludePathPatterns 用户排除拦截
        registry.addInterceptor(globalInterceptor).addPathPatterns("/**")
            .excludePathPatterns("/static/**");
        super.addInterceptors(registry);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }

}

Springboot 获取 yml 数据

有几种方式待我细细道来:

假定我们的 yml 文件中有个这样的配置

info:
  name: Nick

方式一

在属性上使用 @Value("${参数名}")
运行之后,该属性会获取到配置的值 Nick

// 用于组件的属性字段上
@Value("${info.name}")
private String name;

方式二

创建配置属性对象
后续使用,只需要使用对象的属性
就可以获取配置的参数
例如

@Component
@ConfigurationProperties(prefix="info")  // 前缀
public class info {
      // 里面的参数要和yml文件中的相对应
      private String name;
}

方式三

直接使用 Environment 对象

@Autowired
private Environment env;
    
String name = env.getProperty("info.name");

ApplicationContext.getBean 空指针问题解决

在前面的 SpringUtil 对象进行获取对象的时候,报空指针了
有时间加载对象的时候顺序不一样,
所以我要在需要使用 SpringUtil 的类之上添加注解

@DependsOn("SpringUtil")

表示我需要先引用这个,请先给我准备好

SpringBoot 定时任务配置

方式一

静态:基于注解

@Configuration      //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class SaticScheduleTask {
    //3.添加定时任务
    @Scheduled(cron = "0/5 * * * * ?")
    //或直接指定时间间隔,例如:5秒
    //@Scheduled(fixedRate=5000)
    private void configureTasks() {
        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
    }
}

方式二

动态:基于接口

@Configuration      //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class DynamicScheduleTask implements SchedulingConfigurer {

    /**
     * 执行定时任务.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                () -> System.out.println("执行动态定时任务: " + LocalDateTime.now().toLocalTime()),
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    //2.1 获取执行周期
                    String cron = constant.getSyncCron();
                    //2.2 合法性校验.
                    if (StringUtils.isEmpty(cron)) {
                        // Omitted Code ..
                    }
                    //2.3 返回执行周期(Date)
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }
}

SpringBoot 经验书传送地址: https://www.cnblogs.com/inick/p/14389308.html

posted @ 2021-02-08 16:18  iNick  阅读(112)  评论(0编辑  收藏  举报