SpringBoot基本使用
使用springBoot可以不配置过多的xml文件了,全部简化。
一、新建SpringBoot项目
二、SpringBoot配置文件
<!--父依赖,规定了springBoot的版本号-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!--只要是spring-boot开头的,就是子依赖,不需要写版本号-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis等jar包开头的,属于导入依赖,必须版本号-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
配置文件必须是【application.properties
】或者【application.yml
】在里面可以进行任意的配置,二选一,其中properties优先于yml。
使用springBoot可以不需要启动tomcat,使用如下代码启动。
@SpringBootApplication
@MapperScan("com.qianfeng.springboot.ssm.mapper") //相当于我们之前在SSM整合的时候做mapper的扫描,必须到mapper
public class SSMStartApp {
public static void main (String[] args){
SpringApplication.run(SSMStartApp.class,args);
}
}
也可以使用service层进行mapperscan的扫描
@Service("userService")
@MapperScan("com.rj.dao")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public List<User> findAll() {
return userDao.findAll();
}
}
注意,SpringBootApplication启动扫描范围是该类所在父包的所有子包和子类。如图,只能在【com.rj.springboot01
】下创建项目。
三、dao层的使用
mapper都是需要xml文件书写sql语句的,这里,需要在【application.properties
】或者【application.yml
】中配置mybatis的mapper文件路径
将mapper文件放到resources文件下的mapper包中
spring:
datasource:
# url:jdbc:mysql:///mydb9?useSSL=true&characterEncoding=utf8
url: jdbc:mysql://localhost:3306/mydb9?serverTimezone=UTC&useSSL=true&characterEncoding=utf8
username: root
password: 123456
# driver-class-name:com.mysql.cj.jdbc.Driver
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
mybatis:
# 扫描路径
mapper-locations: classpath:mapper/*.xml
除了该方法,也可以在mapper接口方法上注解实现
public interface UserMapper {
@Select("SELECT * FROM tb_user WHERE user_id = #{id} ")
TbUser getUserById(@Param("id") Long id);
}
四、springBoot项目启动方式
- 运行main方法启动springBoot项目
- 通过maven指令启动
mvn spring-boot:run
五、springBoot项目启动方式
- 运行main方法启动springBoot项目
- 通过maven指令启动
mvn spring-boot:run
- 将springboot打包,通过jar文件运行
java -jar xxx.jar
六、测试类
springBoot有自己的测试类,使用的时候需要注意:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Provider01StartApp.class)
public class UserTest {
@Autowired
private UserService userService;
@Test
public void testFindAll() {
List<User> users = userService.findAll();
for (User user : users) {
System.out.println(user.toString());
}
}
}
SpringBootTest中必须配置classes
,且该类为前面提到的AppStart的启动类
七、lombok的问题
使用聚合项目的时候,运行结果导致lombok失效,解决办法: