一、整合Junit
1.pom引入依赖
<!--引入junit起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
2.创建测试类目录
@RunWith(SpringRunner.class)
@SpringBootTest // 加载 HelloApplication 启动类,初始化环境
public class QuickTest {
@Autowired
private User user;
@Test
public void test01() throws Exception {
System.out.println(user);
}
}
二、整合SpringMVC静态资源
现在,我们的项目是一个jar工程,那么就没有webapp
springboot启动时,加载
org.springframework.boot.autoconfigure.web.ResourceProperties
资源属性类
三、拦截器配置
1.自定义一个springMVC拦截器类,实现 HandlerInterceptor
接口
@Component
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
System.out.println("拦截了请求...");
return false;
}
}
2.自定义一个springMVC的配置类,实现WebMvcConfigurer
接口
@Configuration // 自定义配置类,添加拦截器
public class WebConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor)
.addPathPatterns("/**") // 指定拦截路径
.excludePathPatterns("/a1.png"); // 放行某个资源
}
}
四、整合jdbc和事务
spring中的jdbc连接和事务是配置中的重要一环,只要找到SpringBoot提供的启动器即可
1.pom引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
2.至于事务,SpringBoot中通过注解来控制。就是我们熟知的@Transactional
@Service
public class UserService {
public User queryById(Long id){
// 开始查询
return new User();
}
@Transactional
public void deleteById(Long id){
// 开始删除
System.out.println("删除了: " + id);
}
}
五、整合mybatis
1.连接池
其实,在刚才引入jdbc启动器的时候,SpringBoot已经自动帮我们引入了一个连接池
因此,我们只需要指定连接池参数即可:
yml配置中写:
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/xxx
username: root
password: root
引入pom依赖:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.15</version>
</dependency>
2.mybatis
1.pom引入依赖
<!--mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
2.java写一个方法
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/{id}")
public User findById(@PathVariable("id") Long id) {
return userService.findById(id);
}
}
另外,Mapper接口的位置在application.yml中并不能配置,Mapper接口的扫描有两种实现方式:
①给每一个Mapper接口添加@Mapper
注解,由Spring来扫描这些注解,完成Mapper的动态代理。
@Mapper
public interface UserMapper {
}
②在启动类上添加扫描包注解:
@SpringBootApplication
@EnableTransactionManagement //开启注解事
@MapperScan("cn.xxxx.mapper")
public class Application {
public static void main(String[] args) {
// 启动代码
SpringApplication.run(Application.class, args);
}
}
这种方式的好处是,不用给每一个Mapper都添加注解。