上一节,我们已经介绍过springboot的快速入门(一)了, 如果你没有看上一篇文章, 请看完上篇文章再来看这篇,上一篇的文章地址为: https://mp.weixin.qq.com/s/fS0kAiKzKg0kfMIms9SNLw
6. SpringBoot中使用Mybatis
6.1 总步骤
- 导入依赖:MySQL驱动、Druid依赖、MyBatis与SpringBoot整合依赖、Lombok依赖
- 在Service接口实现类上添加@Service注解
- 在Dao接口上添加@Mapper注解
- 在pom中将dao目录注册为资源目录
- 在配置文件中注册映射文件、实体类别名,及数据源
需求: 完成一个简单的注册功能
6.2 增加maven依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis于spring boot整合依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<!--druid 驱动-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</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>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
6.3 主配置文件
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
mybatis.mapper-locations=classpath:mapper/*.xml
#通过在application.properties中指定POJO扫描包来让mybatis自动扫描到自定义POJO
mybatis.type-aliases-package=com.example.entry
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#用户名和密码这里要注意, 不能根据提示信息生成, 生成data-username是不正确的
spring.datasource.username=ajing
spring.datasource.password=******
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
6.4 注册资源目录
修改pom.xml文件中<resources></resources>, 增加如下
<resources>
<!--注册dao包下mybatis映射文件为资源目录-->
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.*</include>
</includes>
</resource>
<!--注册webapp目录为资源目录-->
<resource>
<directory>src/main/webapp</directory>
<targetPath>META-INF/resources</targetPath>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
6.5 项目的github地址:
https://github.com/ajing2/springBoot
7. SpringBoot对事物的支持
若工程直接或间接依赖于 spring-tx,则框架会自动注入 DataSourceTransactionManager
事务管理器;若依赖于 spring-boot-data-jpa,则会自动注入 JpaTransactionManager。
7.1 开启事物
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@EnableTransactionManagement//开启事物
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
7.2 在service实现类中实例事物注解
package com.example.service;
import com.example.entry.Student;
import com.example.dao.SomeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
/**
* @ClassName SomeServiceImpl
* @Description TODO
* @Author lingxiangxiang
* @Date 5:30 PM
* @Version 1.0
**/
@Service("someService")
public class SomeServiceImpl implements SomeService{
@Resource
private SomeDao someDao;
@Override
@Transactional(rollbackFor = Exception.class)// 使用事物的注解, 默认提交方式, 发生异常进行回滚
public void addStudent(Student student) {
someDao.addStudent(student);
}
@Override
public List<Student> queryStudent(Student student) {
return someDao.queryStudent(student);
}
}
8. SpringBoot下使用拦截器
在非 Spring Boot 工程中若要使用 SpringMVC 的拦截器,在定义好拦截器后,需要在 Spring 配置文件中对其进行注册。但 Spring Boot 工程中没有了 Spring 配置文件,那么如何使用拦 截器呢?
Spring Boot 对于原来在配置文件配置的内容,现在全部体现在一个类中,该类需要继承 自 WebMvcConfigurationSupport 类,并使用@Configuration 进行注解,表示该类为一个 JavaConfig 类,其充当配置文件的角色。
8.1 定义拦截器
package com.example.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @ClassName SomeInterceptor
* @Description TODO
* @Author lingxiangxiang
* @Date 3:02 PM
* @Version 1.0
**/
public class SomeInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("执行拦截器preHandle" + request.getRequestURI());
return true;
// 如果返回true, 可以执行后面的函数, 如果返回false, 就会停止
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("执行拦截器postHandle" + request.getRequestURI());
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("执行拦截器afterCompletion" + request.getRequestURI());
}
}
8.2 定义controller
package com.example.controller;
import com.example.common.ResultBean;
import com.example.entry.Student;
import com.example.service.SomeService;
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.util.List;
/**
* @ClassName SomeController
* @Description TODO
* @Author lingxiangxiang
* @Date 5:12 PM
* @Version 1.0
**/
@RestController
@RequestMapping("/some")
public class SomeController {
@Autowired
private SomeService someService;
@RequestMapping("/add")
public @ResponseBody
ResultBean<Object> addStudent(Student student) {
someService.addStudent(student);
return ResultBean.result(200, "success", null);
}
@RequestMapping("/query")
public @ResponseBody ResultBean<Object> queryStudent(Student student) {
List<Student> data = someService.queryStudent(student);
return ResultBean.result(200, "success", data);
}
}
8.3 定义配置类文件
package com.example.interceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* @ClassName MywebMvcConfiguration
* @Description TODO
* @Author lingxiangxiang
* @Date 3:10 PM
* @Version 1.0
**/
@Configuration
public class MywebMvcConfiguration extends WebMvcConfigurationSupport {
@Override
protected void addInterceptors(InterceptorRegistry registry) {
SomeInterceptor someInterceptor = new SomeInterceptor();
registry.addInterceptor(someInterceptor)
.addPathPatterns("/some/query")
.excludePathPatterns("/some/add");
}
}
9. SpringBoot对日志的控制
9.1 logback日志技术介绍
Spring Boot中使用的日志技术为logback. 其与Log4J都出自同一人, 性能能要优于Log4J, 是Log4J的替代者
在Spring Boot中如要使用logback, 则需要具有spring-boot-start-logging依赖, 而该依赖被spring-boot-starter-web所依赖, 即不用直接导入spring-boot-starter-logging依赖
9.2 spring boot中使用logback
在spring boot中使用logback日志, 有两种方式:
- 添加配置属性
只需要在核心配置文件中添加如下配置即可.
# logback日志控制
logging:
#指定日志显示的位置和格式
pattern:
console: logs-%level %msg%n
level:
#较少项目启动时的日志输出
root: warn
#显示指定dao包中类的执行日志
com.abc.dao: debug
注意,在日志显示格式的属性值前面的 logs-是随意内容。在 yml 文件中的属性值若以%开头会报错,所以添加一些随意字符。在 properties 文件中不存在该问题
- 添加配置文件
改文件名为: logback.xml, 且必须要放在src/main/resources类路径下.
logback.xml
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%-5level - %msg%n</pattern>
</encoder>
</appender>
<root level="WARN">
<appender-ref ref="STDOUT" />
</root>
<logger name="com.abc.dao" level="DEBUG" />
</configuration>
9.4 在代码中使用logback
/** Logger实例 */
static final Logger logger = LoggerFactory.getLogger(AbcLogbackDemoApplicationTests.class);
来源:oschina
链接:https://my.oschina.net/u/4292686/blog/4516986