SpringBoot框架基础开发

大家好,最近在学习和回顾SpringBoot框架的知识,顺便写一写学习的步骤方法和知识点。热爱开源技术,分享技术人生。

一 SpringBoot的简介

SpringBoot是所有基于Spring开发的项目的起点。SpringBoot的设计就是为了尽可能快的把Spring框架的应用程序跑起来,减少你的配置文件。
它的本质就是 约定优于配置(Convention over Configuration),又称按约定编程,是一种软件设计范式。简单来说就是遵循约定。

二 SpringBoot解决的问题

我们说一个优秀框架肯定是带给我们开发便利,解决了普遍项目搭建开发复杂的一些问题才会得到开发者的欢迎。那SpringBoot给我们开发带来的什么便利呢?

1.起步依赖
起步依赖本质上是一个Maven项目对象模型,定义了对其他库的传递依赖,这些东西加在一起即支持某项功能。
简单的说,起步依赖就是将具备某种功能的坐标打包到一起,并提供一些默认的功能。
2.自动装配
springboot的自动配置,值的是springboot,会自动将一些配置类的bean注册进ioc容器,我们可以需要的地方使用@autowired或者@resource等注解来使用它。
“自动”的表现形式就是我们只需要引我们想用功能的包,相关的配置我们完全不用管,springboot会自动注入这些配置bean,我们直接使用这些bean即可。

换言之,SpringBoot可以简单地看成简化了的、按照约定开发的SSM(H)等。 简单、快速、方便的搭建项目,对主流开发框架无配置集成,极大的提高了开发、部署效率。 可是呢,最好还是有 SSM(H)的基础,否则其中用到了Spring MVC,Mybatis,Hibernate的地方,或觉得摸不着头脑。

三 SpringBoot项目创建

下面通过IDEA来创建一个简单的IDEA项目,IDEA 本身自带对SpringBoot支持的插件,不像Eclipse那样,要用插件还需要从第三方安装:
**1.菜单 -> New -> Project -> Spring Initializr 然后点 Next **
在这里插入图片描述
2.填写组织结构后next
在这里插入图片描述

3.选择项目的依赖项后next
在这里插入图片描述
4.创建完后springboot项目结构如下图:
在这里插入图片描述
5.编写一个HelloController类测试
在com.example.springboot_demo.controller包下创建一个HelloController控制类,并通过@RequestMapping("/hello")提供一个请求地址。

package com.example.springboot_demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello() {
        return "hello spring Boot";
    }
}

6.测试并运行项目
接下来就运行 SpringbootDemoApplication.java, 然后访问地址:
http://127.0.0.1:8080/hello
在这里插入图片描述
页面输出的内容是“hello spring Boot”,至此,SpringBoot项目构建完成。

四 单元测试

SpringBoot对项目的单元测试提供了很好的支持,在使用时,需要提前在项目的pom.xml文件中添加spring-boot-starter-test测试依赖启动器,可以通过相关注解实现单元测试。
1.添加spring-boot-starter-test测试依赖启动器
在项目的pom.xml文件中添加spring-boot-starter-test测试依赖启动器,示例代码如下:

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-test</artifactId>
 <scope>test</scope>
</dependency>

注意:使用Spring Initializr方式创建的Spring Boot项目,会自动加人spring-boot-starter-test测试依赖启动器,无需手动添加

2.编写单元测试类和测试方法
1)在上面创建的SpringBoot项目的测试类上添加@RunWith(SpringRunner.class)测试启动器注解和@SpringBootTest(classes = Application.class)标记为单元测试类注解
2)通过@Autowired自动装配 HelloController,来调用方法
3)test 方法加上 @Test 注解后编写测试方法,就可以运行测试方法
代码示例:

@RunWith(SpringRunner.class)
@SpringBootTest 
class SpringbootDemoApplicationTests {
 @Autowired
 private HelloController helloController;
 @Test
 void contextLoads() {
 String str= helloController.hello();
 System.out.println(str);
 }
}

五 热部署

Springboot提供了热部署的方式,当发现任何类发生了改变,马上通过JVM类加载的方式,加载最新的类到虚拟机中。 这样就不需要重新启动也能看到修改后的效果了。话不多说,直接上代码:
1. 添加spring-boot-devtools热部署依赖启动项
在SpringBoot项目进行热部署测试之前,需要现在项目的pom.xml文件中添加spring-boot-devtools热部署依赖启动器:

<--引入热部署启动依赖-->
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-devtools</artifactId>
</dependency>

2. IDEA工具热部署设置
选择IDEA工具界面的【file】->【Settings】选择,打开Compiler面板设置页面,如下图设置,点击OK
在这里插入图片描述然后在项目任意位置使用快捷键“ Ctrl+Shift+Alt+/ ”打开Maintenance选择框,选中并打开Registry页面,设置如下图
在这里插入图片描述3. 重启项目测试热部署
重新启动项目,修改HelloController的返回内容,刷新测试

六 全局配置文件

使用Spring Initializr方式创建的Spring Boot项目时,会在resource目录下自动生成一个空的application.properties文件,SpringBoot项目启动时会自动加载application.properties文件。我们可以在application.properties文件中定义SpringBoot项目的相关属性,包括系统属性,环境变量,命令参数等等,也可以自定义配置文件的名称和位置,如下图:

server.port=8081
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.config.additional-location=
spring.config.location=
spring.config.name=application

现在大家发现,在springboot里还是要用到配置文件的。 除了使用.properties外,springboot还支持 yml格式。
个人觉得yml格式的可读性和…properties比起来差不多,有时候还没有不如properties 看起来那么规整。yml格式的文件扩展名可以使用.yml和.yaml两种。
但是考虑到很多springboot项目会使用yml格式,还是简单讲讲,主要目的还是为了读懂其他人的项目。
在application.yml 文件书写注意:

  1. 不同“等级” 用冒号隔开
  2. 次等级的前面是空格,不能使用制表符(tab)
  3. 冒号之后如果有值,那么冒号和值之间至少有一个空格,不能紧贴着
spring:
    mvc:
        view:
            prefix: /WEB-INF/jsp/
            suffix: .jsp
server:
    port: 8888
    context-path: /test

七 SpringBoot的数据访问

SpringBoot默认采用整合SpringData的方式统一处理数据访问层,通过添加大量自动配置,引入各种数据访问模板以及统一的Repositiry接口,从而达到简化数据访问层的操作。
Spring Data提供了多种类型的数据库支持,对支持的数据库进行了整合管理,提供了各种依赖启动器,下面通过一张表罗列出常见数据库依赖启动器,如表所示。

名称描述
spring-boot-starter-data-jpa使用SpringDataJPA与Hibernate
spring-boot-starter-datamongodb使用MongoDB和Spring Data MongoDB
spring-boot-starter-data-neo4j使用Neo4j图数据库和Spring Data Neo4j
spring-boot-starter-data-redis使用Redis键值数据存储和Spring Data Redis和jedis客户端

除此之外,还有一些框架,SpringData项目并没有统一管理,SpringBoot官方也没有提供对应的依赖启动器,但是为了迎合市场开发需求,这些框架技术开发团队自己适配了对应的依赖启动器,例如:mybatis-spring-boot-starter支持MyBatis的使用。

7.1 SpringBoot整合MyBatis

1. 创建项目,引入相应的启动器
在这里插入图片描述
2.创建数据库表,编写实体类

public class Comment {
 private Integer id;
 private String content;
 private String author;
 private Integer aId;
 // 省略get和set方法
 // 省略toString方法
}

3. 编写配置文件application.properties连接数据库

spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?
serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root

4.编写Mapper接口

@Mapper
//标识该接口是mybatis的接口文件,并且让springboot能够扫描到该接口,生成该接口的代理对象,存到容器中
public interface CommentMapper {

    //根据id查询对应评论信息
    @Select("select * from t_comment where id = #{id}")
    public Comment findById(Integer id);

}

5.测试方法

@RunWith(SpringRunner.class)
@SpringBootTest
class Springboot03DataApplicationTests {

    @Autowired
    private CommentMapper commentMapper;

    @Test
    void contextLoads() {
        Comment comment = commentMapper.findById(1);
        System.out.println(comment);
    }
}

结果如下:
在这里插入图片描述
控制台中显示的aId为空,没有映射成功,这是因为编写的实体类中使用了驼峰命名规则将t_comment的t_id字段设计成了aId属性,无法正确映射查询结果。
为了解决上述说的问题,需要在application.properties配置文件中添加开启驼峰命名规则映射配置,如下:

# 开启驼峰命名规则
mybatis.configuration.map-underscore-to-camel-case = true

6.通过xml方式整合Mybatis
上面我们使用的是注解方法把sql写在mapper接口方法上,当然也可以把sql写在配置文件中。把sql写在配置文件中需要在application.properties配置文件中添加配置文件映射路径和实体别名映射路径,如下:

<?xml version="1.0" encoding="UTF-8" ?>
 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.Comment">
 <select id="findById" parameterType="int" resultType="Comment">
 select * from t_comment where id = #{id}
 </select>
</mapper>
#配置mybatis配置文件映射路径
mybatis.mapper-locations=classpath:mapper/*.xml
#配置xml中指定实体对象的别名
mybatis.type-aliases-package=com.example.pojo

通过这两步同样可以达到上面效果,可自测。

7.2 SpringBoot整合JPA

1.在pom.xml文件中添加Spring Data Jpa依赖启动器

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

2.编写实体类

@Entity(name = "t_comment") //设置ORM实体类,并映射表明
public class Comment {
 @Id // 标明主键
 @GeneratedValue(strategy = GenerationType.IDENTITY) // 主键增长策略
 private Integer id;
 private String content;
 private String author;
 @Column(name = "a_id") //指定映射字段名,与数据库一致可以不必指定,默认属性名
 private Integer aId;
 // 省略get和set方法
 // 省略toString方法
 }

3.编写Repository接口,也就是DAO层接口

public interface CommentRepository extends JpaRepository<Comment,Integer> {
}

4.编写测试方法

@Autowired
 private CommentRepository repository;
 @Test
 public void selectComment() {
 Optional<Comment> optional = repository.findById(1);
 if(optional.isPresent()){
 System.out.println(optional.get());
 }
 System.out.println();
 }

选中上面执行测试方法,可在控制台看到打印结果,到此整合JPA完成。

7.3 SpringBoot整合Redis

1.添加redis依赖启动器

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.编写实体类

@RedisHash(value = "persons") //指定实体类对象在redis中的存储空间
public class Person {

    @Id // 用来标识实体类主键  字符串形式的hashkey标识唯一的实体类对象id
    private String id;
    @Indexed // 用来标识对应属性在redis中生成二级索引
    private String firstname;
    @Indexed
    private String lastname;
    private Address address;
  // 省略get和set方法
  // 省略toString方法
}

public class Address {

    @Indexed
    private String city; //城市
    @Indexed
    private String country; //国家
    // 省略get和set方法
    // 省略toString方法
}

3.编写Repository接口,也就是DAO层接口
这里注意:JPA继承的是JpaRepository,而redis继承的是CrudRepository

public interface PersonRepository extends CrudRepository<Person,String> {

    // 根据城市信息查询对应的人
    List<Person> findByAddress_City(String name);
}

4.在全局配置文件中配置redis连接

#配置redis的连接配置

#redis服务器地址
spring.redis.host=127.0.0.1
#redis服务器连接端口
spring.redis.port=6379
#redis服务器连接密码
spring.redis.password=

5.编写测试方法

 //测试整合redis
    @Autowired
    private PersonRepository personRepository;

    @Test
    public void savePerson(){
        Person person = new Person();
        person.setFirstname("张");
        person.setLastname("三");

        Address address = new Address();
        address.setCity("北京");
        address.setCountry("中国");
        person.setAddress(address);

        // 向redis数据库中添加了数据
        personRepository.save(person);

    }

选中上面执行测试方法,可在控制台看到打印结果,到此整合Redis完成。

八 SpringBoot的视图技术Thymeleaf

SpringBoot框架对很多常用的模板引擎技术(如:FreeMarker、Thymeleaf、Mustache等)提供了支持。SpringBoot不太支持常用的JSP模板,也没有提供相应的整合配置,这是因为使用嵌入式Servlet容器的SpringBoot项目对JSP模板存在一些限制,具体原因可百度。SpringBoot的默认视图支持是Thymeleaf,下面就来看看SpringBoot整合Thymeleaf的步骤:

8.1Thymeleaf的常用语法和表达式

th:标签说明
th:insert布局标签,替换内容引入的文件
th:replace页面片段包含(类似JSP中的include标签)
th:each元素遍历
th:if条件判断,如果为真
th:unless条件判断,如果为假
th:switch条件判断,进行选择匹配
th:case条件判断,进行选择匹配
th:value属性值修改,指定标签属性值
th:href用于设置链接地址
th:src用于设定链接地址
th:text用于指定标签显示的文本内容

标准表达式

说明表达式语法
变量表达式${…}
选择变量表达式*{…}
消息表达式#{…}
链接URL表达式@{…}
片段表达式~{…}

8.2 SpringBoot整合Thymeleaf使用

1.引入Thymeleaf依赖

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2.在全局配置文件application.properties中配置thymeleaf模板参数

# 设置thymeleaf模板参数
# 是否启用模板缓存
spring.thymeleaf.cache = false
# 模板编码
spring.thymeleaf.encoding = UTF-8
# 应用于模板的模式
spring.thymeleaf.mode = HTML5
# 指定模板页面存放路径
spring.thymeleaf.prefix = classpath:/templates/
# 指定模板后缀
spring.thymeleaf.suffix = .html

3.编写controller类,跳转页面

@Controller
public class LoginController {
    @RequestMapping("/toLoginPage")
    public String toLoginPage(Model model){

        model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        return "login";
    }
}

4.创建模板文件,引入静态资源
在“classpath:/templates/“目录下创建login.html模板

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1,shrink-to-fit=no">
    <title>用户登录界面</title>
    <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/login/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<!--  用户登录form表单 -->
<form class="form-signin">
    <img class="mb-4" th:src="@{/login/img/login.jpg}" width="72" height="72">
    <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">请登录</h1>
    <input type="text" class="form-control"
           th:placeholder="#{login.username}" required="" autofocus="">
    <input type="password" class="form-control"
           th:placeholder="#{login.password}" required="">
    <div class="checkbox mb-3">
        <label>
            <input type="checkbox" value="remember-me"> [[#{login.rememberme}]]
        </label>
    </div>
    <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.button}">登录</button>
    <p class="mt-5 mb-3 text-muted">© <span th:text="${currentYear}">2019</span>-<span th:text="${currentYear}+1">2020</span></p>
</form>
</body>
</html>

5.效果展示
在这里插入图片描述
SpringBoot的内容远远不止这些,这里只是列举一些简单常用的,还有比如SpringBoot的异常处理、SpringBoot Restful 、缓存管理等等,后面有时间再补充吧。。。

总结

讲完上面这些内容你是否掌握了Springboot 的基本应用,内容不是很多,还是需要自己深刻去理解,多多练习,那你就里掌握不远了。
最后说一下,我觉得学习新的知识就得是完善的课程体系,具实操性的作业练习,还需要自己的提炼和巩固。后续还会继续分享自己的学习笔记和心得。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值