【Springboot学习】从零开始学习Springboot(五)
作者:互联网
Springboot整合Junit
- 注入测试对象(使用@Autowired注解进行装配)
@SpringBootTest public class testCalculate { @Autowired private Calculate c = new Calculate(); }
-
执行要测试的方法
@SpringBootTest public class testCalculate { @Autowired private Calculate c = new Calculate(); @Test public void testAdd(){ int resultA = c.add(1,2); Assert.assertEquals(3,resultA); } }
解决测试类与引导类处于不同包导致报错
在@SpringBootTest注解中指明引导类
@SpringBootTest(classes = Springboot0104Application.class)
public class testCalculate {
@Autowired
private Calculate c = new Calculate();
@Test
public void testAdd(){
int resultA = c.add(1,2);
Assert.assertEquals(3,resultA);
}
}
Springboot整合mybatis
- 创建新模块,选择Spring初始化并配置模块相关基础信息
- 选择当前模块需要使用的技术集(Mybatis、MySQL)
- 设置数据源参数
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/sqllearning username: root password: root
- 定义数据层接口与映射配置
@Mapper public interface RookRoll { @Select("select * from cust_info where cust_id = #{id}") public Rook getById(String id); }
- 测试类中注入接口进行测试
@SpringBootTest class Springboot0105MybatisApplicationTests { @Autowired private RookRoll rookRoll; @Test void contextLoads() { System.out.println(rookRoll.getById("C00100101")); } }
Springboot整合mybatis plus
- 手动添加Springboot整合Mybatis-plus的坐标,可以通过mvnresposity获取
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3</version> </dependency>
- 定义数据层接口与映射配置,继承BaseMapper
@Mapper public interface Rock extends BaseMapper<CustInfo> { }
- 其余的与springboot整合mybatis相同(略)
- 测试
@SpringBootTest class Springboot0106MybatisPlusApplicationTests { @Autowired private Rock rock; @Test void contextLoads() { System.out.println(rock.selectList(null)); }
注意
mybatis plus在类内根据字段名定义变量名时要采用驼峰式定义法,例如字段名为cust_id,那么变量名应为custId,mp会自动将驼峰式变量名映射到下划线式的字段名(mybatis不需要这么做)
Springboot整合Druid
- 导入druid的starter
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.6</version> </dependency>
- 配置druid
spring: datasource: druid: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/sqllearning username: root password: root
整合第三方技术的通用方式
- 导入对应的starter(在idea里直接勾选或者去mvn仓库找)
- 根据提供的配置格式,配置非默认值对应的配置项
标签:Springboot,public,学习,SpringBootTest,从零开始,mybatis,class,Calculate 来源: https://www.cnblogs.com/tnxts/p/16440087.html