SpringBoot学习笔记整理
学习课程链接:
最强SpringBoot实战教程内容通俗易懂springboot微服务开发实战SpringBoot2.x全套完整版
课程配套讲义链接:
SpringBoot讲义
提取码:1234
1、创建一个SpringBoot框架的web项目
2、SpringBoot框架集成SpringMVC(相关依赖)
<!--springboot父工程GAV-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.9</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!--当前项目GAV-->
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--SpringBoot框架 web项目 起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--SpringBoot框架 测试 起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!--SpringBoot框架 编译打包 的插件-->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.5.9</version>
</plugin>
</plugins>
</build>
3、核心配置文件application.properties
#配置Tomcat端口号
server.port=8080
#配置项目上下文根
server.servlet.context-path=/
#jsp视图解析器
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
#设置连接数据库的配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123
#设置MyBatis映射文件的路径
#mybatis.mapper-locations=classpath:mapper/*.xml
4、SpringBoot框架集成JSP
- pom文件添加依赖和资源路径
- properties配置文件设置视图解析器
- controller视图解析jsp页面
- webapp放index.jsp文件
(1) pom文件添加依赖和资源路径
添加依赖
<!--引入SpringBoot内嵌的Tomcat对JSP的解析包,不加解析不了jsp-->
<!--如果只是使用JSP页面,可以只添加该依赖-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
添加资源路径
<!--SpringBoot要求jsp文件必须编译到指定的 META-INF/resources目录下才能访问,否则访问不到。-->
<resource>
<!--源文件位置-->
<directory>src/main/webapp</directory>
<!--指定编译到 META-INF/resources,该目录不能随便写-->
<targetPath>META-INF/resources</targetPath>
<!--指定要把哪些文件编译进去,**表示 webapp 目录及子目录,*.*表示所有文件-->
<includes>
<include>*.*</include>
</includes>
</resource>
(2) properties配置文件设置视图解析器
#jsp视图解析器
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
(3) controller视图解析jsp页面
这里不加@ResponseBody 返回jsp视图
加上 @ResponseBody,返回字符串(重要)
@Controller
public class IndexController {
@RequestMapping("/index")
public String index(Model model){ //Model打开jsp页面视图
model.addAttribute("message","HelloWorld!");
return "index";
},
}
(4) 设置webapp,放jsp文件
- FIle – Project Structure – Modules – Web – Web Resource Directories下添加webapp文件夹路径 – Apply – webapp图标变成蓝点
- 在webapp中添加index.jsp文件
5、SpringBoot框架集成MyBatis
(1)pom文件添加MyBatis依赖和mysql驱动
<!-- MySQL驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- MyBatis整合SpringBoot框架的起步依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
(2)使用MyBatis的逆向工程生成实体bean、映射文件、Dao接口
- powerDesign设计数据库并生成SQL文件
- Navicat连接mysql,执行SQL文件生成数据
- IDEA项目根路径下添加并修改GeneratorMapper.xml 配置文件
- pom文件添加MyBatis插件,双击插件,生成相关文件
GeneratorMapper.xml 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 指定连接数据库的 JDBC 驱动包所在位置,指定到你本机的完整路径 -->
<classPathEntry location="C:\Users\wano\.m2\repository\mysql\mysql-connector-java\8.0.28\mysql-connector-java-8.0.28.jar"/>
<!-- 配置 table 表信息内容体,targetRuntime 指定采用 MyBatis3 的版本 -->
<context id="tables" targetRuntime="MyBatis3">
<!-- 抑制生成注释,由于生成的注释都是英文的,可以不让它生成 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 配置数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/springboot?nullCatalogMeansCurrent=true"
userId="root"
password="123">
</jdbcConnection>
<!-- 生成 model类 bean
targetPackage指定model类的包名,
targetProject指定生成的model放在哪个工程下面-->
<javaModelGenerator targetPackage="com.example.model"
targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="false" />
</javaModelGenerator>
<!-- 生成 MyBatis 的 Mapper.xml 文件,
targetPackage 指定 mapper.xml 文件的包名,
targetProject 指定生成的 mapper.xml 放在哪个工程下面 -->
<sqlMapGenerator targetPackage="com.example.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成 MyBatis 的 Mapper文件,
targetPackage 指定 Mapper 接口类的包名,
targetProject 指定生成的 Mapper 接口放在哪个工程下面 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.example.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 数据库表名及对应的 Java 模型类名 -->
<table tableName="t_student" domainObjectName="Student"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
pom文件添加MyBatis插件
<!--mybatis 代码自动生成插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<!--配置文件的位置-->
<configurationFile>GeneratorMapper.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
(3)前后端操作数据库并展示
- @Controller、service接口、@Service、@Mapper
(或@MapperScan(“com.example.mapper”)) - pom.xml 文件中手动指定resources路径 (或把mapper.xml放到resource的mapper文件夹中,配置properties文件)
- 运行,展示页面数据
(1)controllor控制层
自动注入Service类,添加@Controller注解
@Controller
public class StudentControllor {
@Autowired
private StudentService studentService;
@RequestMapping("/student")
@ResponseBody
public Object student(int id){
Student student = studentService.getStudentById(id);
return student;
}
@RequestMapping("/say")
@ResponseBody
public String say(){
return "hello 万季玲";
}
}
(2)Service业务层 – 接口和对应实现类
接口和抽象方法
package com.wano.service;
import com.wano.model.Student;
public interface StudentService {
/**
* 根据学生ID查询详情
*/
Student queryStudentById(Integer id);
}
对象实现类和方法,自动注入Mpper类,添加注解@Service
package com.wano.service.impl;
import com.wano.mapper.StudentMapper;
import com.wano.model.Student;
import com.wano.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public Student queryStudentById(Integer id) {
return studentMapper.selectByPrimaryKey(id);
}
}
(3)Mpper和Mpper.xml是自动生成的,只用添加注解@Mpper即可调用方法。
(4)使用Mpper.xml的两种方法:
方法一:手动配置pom.xml文件
<!--手动指定文件夹为resource,将mapper.xml读入资源文件夹中-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
方法二:把mapper.xml放到resource的mapper文件夹中,配置properties文件
#设置MyBatis映射文件的路径
#mybatis.mapper-locations=classpath:mapper/*.xml
6、Springboot支持事务
@Transactional 放在service方法的头部
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Transactional //事务注解
@Override
public int updataStudentById(Student student) {
//成功
int res = studentMapper.updateByPrimaryKey(student);
//失败
int a = 10/0;
return res;
}
}
7、常用注解
- @RestController 相当于类上加@Controller+方法上加@ResponseBody,意味着当前控制层类中所有的方法返回的都是JSON对象
- @GetMapping 查询
- @PostMapping 新增
- @DeleteMapping 删除
- @PutMapping 更新
【注】测试工具:Postman测试工具
//@Controller
@RestController //相当于类上加@Controller+方法上加@ResponseBody
//意味着当前控制层类中所有的方法返回的都是JSON对象
public class StudentController {
@Autowired
private StudentService studentService;
//该方法请求方式支持:GET和POST请求
//RequestMapping("/studentStudentById")
@RequestMapping(value = "/studentStudentById",method = {RequestMethod.GET,RequestMethod.POST})
public Object studentStudentById(Integer id){
Student student = studentService.queryStudentById(id);
return student;
}
//该方法只支持:GET请求
//@RequestMapping(value = "/studentStudentById2",method = {RequestMethod.GET})
//该注解在查询数据时使用 -->查询
@GetMapping("/studentStudentById2")
public Object studentStudentById2(){
return "only get method";
}
//该方法只支持:POST请求
//@RequestMapping(value = "/insert",method = {RequestMethod.POST})
//该注解在添加数时据使用 -->新增
@PostMapping("/insert")
public Object insert(){
return "insert success";
}
//该方法只支持:DELETE请求
//@RequestMapping(value = "/delete",method = {RequestMethod.DELETE})
//该注解在删除数时据使用 -->删除
@DeleteMapping("/delete")
public Object delete(){
return "delete success";
}
//该方法只支持:UPDATE请求
//@RequestMapping(value = "/update",method = {RequestMethod.PUT})
//该注解在修改数时据使用 -->更新
@PutMapping("/update")
public Object update(){
return "update info success";
}
}
8、SpringBoot框架使用拦截器Interceptor
(1)定义一个拦截器
定义一个拦截器,实现HandlerInterceptor接口
package com.example.interceptor;
import com.example.model.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("------------------进入拦截器-------------------");
//拦截的规则
//从session中获取用户的信息
User user = (User) request.getSession().getAttribute("user");
//判断用户是否为空
if (null == user){
//未登录,跳转到登录界面
response.sendRedirect(request.getContextPath() + "/user/page/login");
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
(2)创建一个配置类
创建一个配置类,相当于在SpringMVC配置文件中使用mvc:interceptors标签
package com.example.config;
import com.example.interceptor.UserInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration //定义此类为配置文件(相当于一个xml配置文件)
public class InterceptorConfig implements WebMvcConfigurer {
//mvc:interceptors
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 定义拦截路径
String[] addPathPatterns = {
"/user/**"
};
// 排除不需要拦截路径
String[] excludePathPatterns={
"/user/login","/user/page/login","/user/outindex"
};
//mvc:interceptor bean class=""
registry.addInterceptor(new UserInterceptor())
.addPathPatterns(addPathPatterns)
.excludePathPatterns(excludePathPatterns);
}
}
(3)Controller访问验证效果
- 直接访问/user/center,会跳转到/user/page/login
- 接着访问/user/login,相当于登录
- 然后再访问/user/center,会直接显示center内容
package com.example.controller;
import com.example.model.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/user")
public class UserController {
//首页信息,不需拦截
@RequestMapping("/outindex")
public Object out(){
return "outindex see anytime";
}
//用户登录,不需拦截
@RequestMapping(value = "/page/login")
public String loginPage(){
return "Login Page";
}
//用户已登录状态,不需拦截
@RequestMapping("/login")
public Object login(HttpServletRequest request){
//将用户信息存放到session中
User user = new User();
user.setId(1001);
user.setUsername("wano");
request.getSession().setAttribute("user",user);
return "logged!";
}
//中心信息,需要拦截
@RequestMapping("/center")
public Object center(){
return "See Center Info";
}
}
9、SpringBoot框架使用过滤器Filter
- 通过注解的方式创建Filter
- 通过注册组件的方式创建Filter
方式一:通过注解的方式创建Filter
- @WebFilter(urlPatterns = “/myfilter”) //添加过滤请求路径
- @ServletComponentScan(basePackages = “com.example.filter”)
定义一个过滤器类,添加注解及过滤路径
package com.example.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(urlPatterns = "/myfilter") //添加过滤请求路径
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("---------------已进入过滤器---------------");
chain.doFilter(request,response);
}
}
扫描注入
//SpingBoot项目启动入口类
@SpringBootApplication //开启spring自动配置,springboot核心注解
@ServletComponentScan(basePackages = "com.example.filter")
public class Application {
//springboot项目所有代码必须放到Application类的同级目录或下级目录,不能放到上级目录
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
方式二:通过注册组件的方式创建Filter
- 定义一个过滤器类,不需要添加注解
- 定义一个配置类,注册过滤器并添加过滤路径
定义一个过滤器类,不需要添加注解
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("---------------已进入过滤器---------------");
chain.doFilter(request,response);
}
}
定义一个配置类,注册过滤器并添加过滤路径
@Configuration //定义此类为配置类
public class FilterConfig {
@Bean
public FilterRegistrationBean myFilterRegistrationBean(){
//注册过滤器
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new MyFilter());
//添加过滤路径
filterRegistrationBean.addUrlPatterns("/user/*"); //只能写单个*
return filterRegistrationBean;
}
}
10、SpringBoot框架设置字符编码问题
具体问题具体分析
SpringBoot全局字符编码设置(解决乱码问题)
(1)在 servlet 中添加指定编码格式
response.setContextType(“text/html;charset=utf-8”)
@WebServlet(urlPatterns = "/myservlet")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().println("万季玲,Hello,world!");
//设置浏览器编码格式
resp.setContentType("text/html;character=utf-8");
resp.getWriter().flush();
resp.getWriter().close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
(2)定义字符编码配置类
@Configuration
public class SystemConfig {
@Bean
public FilterRegistrationBean characterEncodingFilterRegistrationBean(){
//创建字符编码过滤器
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
//设置强制使用指定字符编码
characterEncodingFilter.setForceEncoding(true);
//设置指定字符编码
characterEncodingFilter.setEncoding("UTF-8");
//注册过滤器
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
//设置字符编码过滤器
filterRegistrationBean.setFilter(characterEncodingFilter);
//设置字符编码过滤器路径
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
}
}
(3)在application.properties中设置
#设置字符编码(解决乱码问题)
server.servlet.encoding.enabled=true
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.force=true
server.tomcat.uri-encoding=UTF-8
11、SpringBoot工程打jar包和war包
- jar包使用内嵌的tomcat,端口号和上下文根就是application.properties中设置的值。
- war包部署到tomcat中,之前application.properties中设置的端口号和上下文根都失效了。
(1)SpringBoot工程打jar包
- pom文件中添加原有资源
- pom文件中指定打jar包的字符
- MAVEN – Lifecycle – clean
- MAVEN – Lifecycle – package
- 复制jar包部署到任意路径下,编译运行jar包
- 直接访问请求路径
【注意】运行jar包,直接访问请求路径,不需要上下文根。
在pom文件中把原有资源添加进来
<resources>
<!--把原有资源添加进来-->
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
pom文件中指定打jar包的字符
<build>
<!--指定打war包的字符-->
<finalName>springboot</finalName>
</build>
MAVEN – Lifecycle – clean
MAVEN – Lifecycle – package
复制jar包部署到任意路径下,编译运行jar包(这里可以写一个run-jar.bat文件启动jar包)
F:\> java -jar springboot.jar
(2)SpringBoot工程打war包
- pom文件中修改打包方式
- pom文件中指定打war包的字符
- pom文件中添加原有资源
- Application 类继承SpringBootServletInitializer ,重写configure方法
- MAVEN – Lifecycle – clean
- MAVEN – Lifecycle – package
- 复制twar包部署到Tomcat的webapps下
- 运行Tomcat,访问项目请求路径
【注意】war包部署到tomcat中,之前application.properties中设置的端口号和上下文根都失效了。
pom文件中修改打包方式
<!--修改打包方式为war-->
<packaging>war</packaging>
pom文件中自动生成编译打包插件,必须得有
<!--SpringBoot框架编译打包的插件-->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.5.9</version>
</plugin>
指定打war包的字符
<build>
<!--指定打war包的字符-->
<finalName>springboot</finalName>
</build>
在pom文件中把原有资源添加进来
<resources>
<!--把原有资源添加进来-->
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
在Application 启动类中继承SpringBootServletInitializer ,重写configure方法
@SpringBootApplication
public class SpringbootApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
//构建新资源,参数为当前Springboot启动类
return builder.sources(SpringbootApplication.class);
}
}
点击MAVEN – Lifecycle – clean ,清除target文件夹
点击MAVEN – Lifecycle – package,打包工程
打包成功后,复制target下的war包到Tomcat目录下的webapps目录下,启动Tomcat,可以在浏览器中正常运行工程项目。
12、SpringBoot集成logback日志
- logback-spring.xml,且放在 src/main/resources 下
- 直接在类上通过注解@Slf4j声明日志对象
- 在 pom.xml 中添加logback日志的依赖
(1)logback-spring.xml,且放在 src/main/resources 下
我们一般针对 DAO 的包进行 DEBUG 日志设置,这样的话,只打印 SQL 语句,同时还要在D:/log下添加springboot-logback.log文件( 在logback-spring.xml中设置,日志文件位置可以修改)
<logger name="com.abc.springboot.mapper" level="DEBUG" />
<?xml version="1.0" encoding="UTF-8"?>
<!-- scan:当此属性设置为 true 时,配置文件如果发生改变,将会被重新加载,默认值为true -->
<!-- scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当 scan 为 true 时,此属性生效。默认的时间间隔为 1 分钟。 -->
<configuration scan="true" scanPeriod="10 seconds">
<!--输出到控制台-->
<appender name="CONSOLE"
class="ch.qos.logback.core.ConsoleAppender">
<!--此日志 appender 是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>debug</level>
</filter>
<encoder>
<Pattern>%date [%-5p] [%thread] %logger{60} [%file : %line] %msg%n</Pattern>
<!-- 设置字符集 -->
<charset>UTF-8</charset>
</encoder>
</appender>
<!--输出到文件-->
<appender name="FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--<File>/home/log/stdout.log</File> 需要修改-->
<File>D:/log/springboot-logback.log</File>
<encoder>
<pattern>%date [%-5p] %thread %logger{60} [%file : %line] %msg%n</pattern>
</encoder>
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 添加.gz 历史日志会启用压缩 大大缩小日志文件所占空间 -->
<!--<fileNamePattern>/home/log/stdout.log.%d{yyyy-MM-dd}.log</fileNam
ePattern>-->
<fileNamePattern>D:/log/springboot-logback.log.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory> <!-- 保留 30天日志 -->
</rollingPolicy>
</appender>
<!--日志文件的范围可以自己设置,这里是mapper文件-->
<logger name="com.wano.springboot.mapper" level="DEBUG" />
<!-- 日志级别从低到高分为 TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果设置为 WARN,则低于 WARN 的信息都不会输出 -->
<!--如果root标签指定了日志级别,以根日志级别为准,如果root没有指定就以追加器为准-->
<!--
1 appender trace trace
root trace
2 appender trace debug
root debug
3 appender trace debug
root 空
4 appender debug info
root info
-->
<!--使用哪个appender,就在这里指定哪个-->
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
</root>
</configuration>
(2)在 pom.xml 中添加logback日志的依赖
<!--@Slf4j 自动化日志对象-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
(3)直接在类上通过注解@Slf4j声明日志对象
在类上加@Slf4j注解,以log.xx()的方式写日志信息
@Controller
@Slf4j //logback日志注解
public class UserController {
@RequestMapping("/user/json/detail")
public @ResponseBody Object userJsonDetail(){
Map<String,Object> retmap = new HashMap<String,Object>();
retmap.put("id",1001);
retmap.put("username","wano");
log.info("添加用户成功"); //log.xx()的方式写日志信息
return retmap;
}
}