SpringBoot进阶02
1. 日志的使用
1.1 基本使用
/** * 获取日志记录器 */ Logger logger = LoggerFactory.getLogger(this.getClass()); @RequestMapping("/hello") @ResponseBody public String sayHello(){ //日志级别 tracelogger.trace("trace...."); logger.debug("debug...."); logger.info("info...."); logger.warn("warn...."); logger.error("error..."); return "hello springBoot!"; }
1.2 yml修改日志级别
在application.yml中(指定到修改的包)
#修改日志级别(默认是info) trace
logging:
level:
cn:
dyier: trace
1.3 指定配置文件配置logback.xml
xml version="1.0" encoding="UTF-8"?> <configuration scan="false" scanPeriod="60 seconds" debug="false"> <property name="LOG_HOME" value="E:/springbootLogs" /> <property name="appName" value="dyier-springboot"/> <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender"> <layout class="ch.qos.logback.classic.PatternLayout"> <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%npattern> layout> appender> <appender name="appLogAppender" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${LOG_HOME}/${appName}.logfile> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${LOG_HOME}/${appName}-%d{yyyy-MM-dd}-%i.logfileNamePattern> <MaxHistory>365MaxHistory> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>100MBmaxFileSize> timeBasedFileNamingAndTriggeringPolicy> rollingPolicy> <layout class="ch.qos.logback.classic.PatternLayout"> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [ %thread ] - [ %-5level ] [ %logger{50} : %line ] - %msg%npattern> layout> appender> <logger name="cn.dyier" level="debug" /> <logger name="org.springframework" level="debug" additivity="false"/> <root level="info"> <appender-ref ref="stdout" /> <appender-ref ref="appLogAppender" /> root> configuration>
1.4 指定配置文件配置logback-spring.xml
xml version="1.0" encoding="UTF-8"?> <configuration scan="false" scanPeriod="60 seconds" debug="false"> <property name="LOG_HOME" value="E:/logback-spring" /> <property name="appName" value="dyier-springboot"/> <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender"> <layout class="ch.qos.logback.classic.PatternLayout"> <springProfile name="dev"> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ----> [%thread] ---> %-5level %logger{50} - %msg%npattern> springProfile> <springProfile name="!dev"> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ==== [%thread] ==== %-5level %logger{50} - %msg%npattern> springProfile> layout> appender> <appender name="appLogAppender" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${LOG_HOME}/${appName}.logfile> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${LOG_HOME}/${appName}-%d{yyyy-MM-dd}-%i.logfileNamePattern> <MaxHistory>365MaxHistory> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>100MBmaxFileSize> timeBasedFileNamingAndTriggeringPolicy> rollingPolicy> <layout class="ch.qos.logback.classic.PatternLayout"> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [ %thread ] - [ %-5level ] [ %logger{50} : %line ] - %msg%npattern> layout> appender> <logger name="cn.dyier" level="info" /> <logger name="org.springframework" level="debug" additivity="false"/> <root level="info"> <appender-ref ref="stdout" /> <appender-ref ref="appLogAppender" /> root> configuration>
1.5 logback.xml与logback-spring的区别
logback.xml:直接就被日志框架识别了
logback-spring.xml:日志框架就不直接加载日志的配置项,由SpringBoot解析日志配置,可以使用SpringBoot的高级Profile功能
1.6 配置文件指定日志写入磁盘的方式
方式一:
logging.file: E:/logback/logs
方式二:
logging.path: E:/logback/logs
1.7 切换日志框架为log4j2
pox.xml取消logback依赖,引入log4j2依赖
<dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-webartifactId> <exclusions> <exclusion> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-loggingartifactId> exclusion> exclusions> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-log4j2artifactId> dependency>
1.8 编写log4j2-spring配置文件
xml version="1.0" encoding="UTF-8"?> <configuration status="WARN" monitorInterval="30"> <appenders> <console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/> console> <File name="log" fileName="log/test.log" append="false"> <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/> File> <RollingFile name="RollingFileInfo" fileName="${sys:user.home}/logs/info.log" filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log"> <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/> <Policies> <TimeBasedTriggeringPolicy/> <SizeBasedTriggeringPolicy size="100 MB"/> Policies> RollingFile> <RollingFile name="RollingFileWarn" fileName="${sys:user.home}/logs/warn.log" filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log"> <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/> <Policies> <TimeBasedTriggeringPolicy/> <SizeBasedTriggeringPolicy size="100 MB"/> Policies> <DefaultRolloverStrategy max="20"/> RollingFile> <RollingFile name="RollingFileError" fileName="${sys:user.home}/logs/error.log" filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log"> <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/> <Policies> <TimeBasedTriggeringPolicy/> <SizeBasedTriggeringPolicy size="100 MB"/> Policies> RollingFile> appenders> <loggers> <logger name="org.springframework" level="INFO"/> <logger name="org.mybatis" level="INFO"/> <root level="all"> <appender-ref ref="Console"/> <appender-ref ref="log"/> <appender-ref ref="RollingFileInfo"/> <appender-ref ref="RollingFileWarn"/> <appender-ref ref="RollingFileError"/> root> loggers> configuration>
2. SpringBoot继承Thymeleaf
2.1 导入依赖
<dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-thymeleafartifactId> dependency>
2.2 创建模板hello.html(文件位置:classpath:templates/hello.html)
<html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Titletitle> head> <body> <h1>成功!h1> <div th:text="${msg}">这是显示欢迎信息div> body> html>
2.3 编写controller
@RequestMapping("/jsp") public String jsp(Model model) { model.addAttribute("msg", "hello jsp"); //会去找classpath:templates/hello.html return "hello"; }
2.4 Thymeleaf的自动配置原理
@EnableAutoConfiguration 开启自动配置功能,通过一个AutoConfigurationImportSelector导入选择器去扫描 spring-boot-autoconfigure-2.0.5.RELEASE.jar 自动配置包下面的 spring.factories 文件中的很多很多的自动配置的类
而:ThymeleafAutoConfiguration 是的Thymeleaf的自动配置 ,在这个自动配置类里面通过一个ThymeleafProperties去读取配置文件中的配置(也有默认配置) ,来自动配置Thymeleaf,比如Thymeleaf的视图解析器的自动配置如下:
@Bean
@ConditionalOnMissingBean(name = "thymeleafViewResolver")
public ThymeleafViewResolver thymeleafViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
...
return resolver;
}
3. 静态资源
3.1 静态资源目录
Classpath:/static(resources/static)
3.2 webjars
导入依赖
<dependency>
<groupId>org.webjars.bowergroupId>
<artifactId>jqueryartifactId>
<version>3.3.1version>
dependency>
3.3 模板导入jquery的js
<script th:src="@{/webjars/jquery/3.3.1/dist/jquery.js}">script>
3.4 配置首页
classpath:/index.html(resources/index.html)
3.5 网站图标
classpath:/favicon.icon(resources/favicon.icon)
4. SpringBoot中的MVC配置
4.1 配置拦截器
定义拦截器
@Configuration public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("前置拦截"); return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("后置拦截"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
4.2 注册拦截器和添加视图控制器
@Configuration public class MyMvcConfig extends WebMvcConfigurerAdapter { @Autowired private LoginInterceptor loginInterceptor; /** * 批量注册拦截器 * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor).addPathPatterns("/**") .excludePathPatterns("/json02/obj"); } /** * 批量注册ViewController * @param registry */ @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/hello").setViewName("hello"); } }
5. 集成DataSource
5.1 导入依赖
mysql mysql-connector-java org.springframework.boot spring-boot-starter-jdbc
5.2 配置文件自动配置datasource
spring:
#配置spring DataSource
datasource:
url: jdbc:mysql:///test
username: root
password: 123456
6. 继承Mybatis
6.1 导入依赖
org.mybatis.spring.boot mybatis-spring-boot-starter 1.1.1
6.2 配置Mybatis包代理(application.yml)
#mybaits包代理
mybatis:
type-aliases-package: cn.dyier.domain, cn.dyier.query
6.3 配置Mapper接口扫描包(@MapperScan)
@MapperScan @SpringBootApplication @MapperScan("cn.dyier.mapper") public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
7. 集成事务
7.1 service上直接打标签
springBoot自动配置类事务。直接打标签即可
@Service @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void save(User user) { userMapper.save(user); } @Override public ListfindAll() { PageHelper.startPage(1, 3); return userMapper.findAll(); } }
8. PageHelper的使用(分页插件)
8.1 导入依赖
<dependency> <groupId>com.github.pagehelpergroupId> <artifactId>pagehelperartifactId> <version>4.1.0version> dependency>
8.2 配置
@Configuration public class MyBatisConfiguration { @Bean public PageHelper pageHelper() { System.out.println("MyBatisConfiguration.pageHelper()"); PageHelper pageHelper = new PageHelper(); Properties p = new Properties(); p.setProperty("offsetAsPageNum", "true"); p.setProperty("rowBoundsWithCount", "true"); p.setProperty("reasonable", "true"); pageHelper.setProperties(p); return pageHelper; } }
8.3 使用
@Override public ListfindAll() { PageHelper.startPage(1, 3); return userMapper.findAll(); }