SpringBoot与jdk9.0好像不太兼容
- 能够理解Spring的优缺点
- 能够理解SpringBoot的特点
- 能够理解SpringBoot的核心功能
- 能够搭建SpringBoot的环境
- 能够完成application.properties配置文件的配置
- 能够完成application.yml配置文件的配置
- 能够使用SpringBoot集成Mybatis
- 能够使用SpringBoot集成Junit
- 能够使用SpringBoot集成SpringData JPA
SpringBoot快速入门
创建Maven工程
使用idea工具创建一个maven工程,该工程为普通的java工程即可
添加SpringBoot的启动器
SpringBoot要求,项目要继承SpringBoot的起步依赖spring-boot-starter-parent
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
SpringBoot要集成SpringMVC进行Controller的开发,所以项目要导入web的启动依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
编写SpringBoot引导类
编写Controller
测试
SpringBoot深度体验
创建配置文件
在maven工程的man/java/resources目录下创建名为“application.yml”的配置文件,其中配置数据库和jpa的相关属性
#DB Configuration:
spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf8
username: root
password: 112358
#JPA Configuration:
jpa:
database: MySQL
show-sql: true
generate-ddl: true
可以直接使用一个静态的html展示数据。例如使用vuejs展示。
动态展示:
页面动态生成,每次请求都生成一次页面。
jsp:本质上就是servlet。servlet运行要求是一个servlet容器中。工程必须是web工程。
需要把工程改造成web工程,打包方式改为war
需要把springboot中嵌入的tomcat排除。
在springboot工程中不推荐使用jsp。
模板技术:
freemarker(推荐使用)
velocity(在springboot中已经过期,推荐使用freemarker)
tymeleaf
使用方法:
1)添加起步依赖
2)创建模板文件,保存位置resources/templates目录下
文件的扩展名必须是ftl
3)编写Controller把查询结果传递给模板。
常见框架整合
1、mybatis
使用方法:
1)添加mybatis的起步依赖。
2)在配置文件中配置数据源信息。
3)编写pojo类、mapper接口、mapper映射文件。
4)手动配置mybatis的包扫描器。
在启动类上添加@MapperScan注解
5)使用
使用mybatis出现如下错误:
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.itheima.mappper.UserMapper.getUserList
原因:接口中的方法没有找到对应的sql语句
解决方案:
1、把映射文件放到resources目录下,对应的创建目录结构。
2、可以修改pom.xml文件,让maven把src/main/java目录下的配置文件也复制到目标目录。
可以配置mybatis的一些参数:
#spring集成Mybatis环境
#pojo别名扫描包
mybatis.type-aliases-package=com.itheima.domain
#加载Mybatis映射文件
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
添加Mybatis的启动器
<!--mybatis起步依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
2、junit
使用方法:
1)添加起步依赖
2)创建一个测试类
3)在测试类上添加
@RunWith(SpringRunner.class)
@SpringBootTest(classes=Application.class)
4)在测试类中注入需要使用的对象即可。
添加Junit的启动器
<!--测试的起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
事务管理
开启事务需要在引导类上添加@EnableTransactionManagement(
低版本上
)
注解,启注解事务管理,等同于xml配置方式的
<tx:annotation-driven />
然后在使用事务的方法或者类上添加@Transactional
注解开启事务。
使用注解@ConfigurationProperties映射
通过注解@ConfigurationProperties(prefix="配置文件中的key的前缀")可以将配置文件中的配置自动与实体进行映射
测试过程:
总体过程: