分布式 第四章 Spring Boot 初步


1 Spring Boot框架入门

简介:SpringBoot采用大量的默认配置,能够简化SSM框架开发过程

特征
➢ 能够快速创建基于 Spring 的应用程序
➢ 能够直接使用 java main 方法启动内嵌的 Tomcat 服务器运行 Spring Boot 程序,不需
要部署 war 包文件
➢ 提供约定的 starter POM 来简化 Maven 配置,让 Maven 的配置变得简单
➢ 自动化配置,根据项目的 Maven 依赖配置,Spring boot 自动配置 Spring、Spring mvc等
➢ 提供了程序的健康检查等功能
➢ 基本可以完全不使用 XML 配置文件,采用注解配置

四大核心

  • 自动配置
  • 起步依赖
  • Actuator健康检查
  • 命令行界面

2 Spring Boot入门案例

入门案例分析
➢ @SpringBootApplication 注解是 Spring Boot 项目的核心注解,主要作用是开启Spring 自动配置,如果在 Application 类上去掉该注解,那么不会启动 SpringBoot程序
➢ @Controller 及 @ResponseBody 依然是我们之前的 Spring MVC,因为 Spring Boot的里面依然是使用我们的 SSM 等框架

核心配置文件
.properties
.yml \ .yaml

多环境配置

application.properties    spring.profiles.active=dev
application-dev.properties
application-product.properties
application-text.properties

自定义配置
在配置文件中添加

website=https://www.rtzhao.fun

可以在Controller类中用 @Value注解获取到自定义配置的值

@Value("${website}")
private String website

当自定义配置项比较多时,可以创建配置类
类加上 Component 和 ConfigurationProperties 注解,
并在 ConfigurationProperties 注解中添加属性prefix,作用可以区分同名配置

@Component
@ConfigurationProperties(prefix = "school")
public class ConfigInfo {
   ...}

再在配置文件中写

school.name=ssm
school.website=https://www.rtzhao.fun

然后再Controller类中 注入配置类,以及修改测试方法

@Autowired
private ConfigInfo configInfo;

@RequestMapping(value = "/springBoot/config")
public @ResponseBody String say() {
   
 return configInfo.getName() + "=======" + configInfo.getWebsit(); }

Spring Boot前端使用JSP

  1. pom.xml中添加依赖
<!--引入 Spring Boot 内嵌的 Tomcat 对 JSP 的解析包,不加解析不了 jsp 页面-->
<!--如果只是使用 JSP 页面,可以只添加该依赖-->
<dependency>
	<groupId>org.apache.tomcat.embed</groupId>
	<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!--如果要使用 servlet 必须添加该以下两个依赖-->
<!-- servlet 依赖的 jar 包-->
<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
	<groupId>javax.servlet.jsp</groupId>
	<artifactId>javax.servlet.jsp-api</artifactId>
	<version>2.3.1</version>
</dependency>
<!--如果使用 JSTL 必须添加该依赖-->
<!--jstl 标签依赖的 jar 包 start-->
<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>jstl</artifactId>
</dependency>
  1. pom.xml的build标签中配置jsp文件编译到点的目录(META_INF/resources)
<resources>
	<resource>
	<!--源文件位置-->
	<directory>src/main/webapp</directory>
	<!--指定编译到 META-INF/resources,该目录不能随便写-->
	<targetPath>META-INF/resources</targetPath>
	<!--指定要把哪些文件编译进去,**表示 webapp 目录及子目录,*.*表示所有文件-->
	<includes>
		<include>**/*.*</include>
	</includes>
	</resource>
</resources>
  1. 在配置文件中配置 Spring MVC的视图展示为jsp
#配置 SpringMVC 视图解析器
#其中:/ 表示目录为 src/main/webapp
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
  1. 在Controller类中编写测试代码
@Controller
public class SpringBootController {
   
@RequestMapping(value = "/springBoot/jsp")
	public String jsp(Model model) {
   
		model.addAttribute("data","SpringBoot 前端使用 JSP 页面!");
	return "index";
} }
  1. 在 src/main 下创建一个 webapp 目录,然后在该目录下新建index.jsp 页面
    使用jstl获取controller方法中传来的数据
<body>
	${data}
</body>

3 Spring Boot框架Web开发

3.1 Spring Boot集成 MyBatis

  1. pom.xml中添加相关依赖
<!--MyBatis 整合 SpringBoot 的起步依赖-->
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>2.0.0</version>
</dependency>

<!--MySQL 的驱动依赖-->
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>
  1. 核心配置文件中配置数据源
#配置内嵌 Tomcat 端口号
server.port=9090
#配置项目上下文根
server.servlet.context-path=/010-springboot-web-mybatis

#配置数据库的连接信息
#注意这里的驱动类有变化
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=t
rue&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyD
atetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
  1. 代码开发

➢ 使用 Mybatis 反向工程生成接口、映射文件以及实体 bean

在StudentMapper 接口上加一个 Mapper 注解
(mybatis自动扫描数据持久层的映射文件及 DAO 接口的关系)
 
或者注销掉@Mapper,在运行主类 Application上加 @MapperScan("com.abc.springboot.mapper")
 
在默认情况下,Mybatis 的 xml 映射文件不会编译到 target 的 class 目录下,
所以我们需要在 pom.xml 文件中配置 resource

有的公司直接将映射文件直接放到 resources 目录下,新建目录 mapper 存放映射文件
并在核心配置文件中指定映射文件的位置,这个配置只有接口和映射文件不在同一个包的情况下,才需要指定 
mybatis.mapper-locations=classpath:mapper/*.xml
<resources>
    <resource>
    <directory>src/main/java</directory>
    <includes>
   	 <include>**/*.xml</include>
    </includes>
    </resource>
</resources>

➢ 在 web 包下创建 StudentController 并编写代码
➢ 在 service 包下创建 service 接口并编写代码
➢ 在 service.impl 包下创建 service 接口并编写代码

3.2 Spring Boot事务支持

底层采用的是 Spring 本身提供的事务管理

➢在 StudentServiceImpl 接口实现类中对更新学生方法进行实现,并构建一个异常,
同时在该方法上加 @Transactional 注解

@Override
@Transactional //添加此注解说明该方法添加的事务管理
public int update(Student student) {
   
	int updateCount = studentMapper.updateByPrimaryKeySelective(student);
	System.out.println("更新结果:" + updateCount);
	//在此构造一个除数为 0 的异常,测试事务是否起作用
	int a = 10/0;
 return updateCount; }

➢在 Application类上加@EnableTransactionManagement开启事务支持

@SpringBootApplication
@MapperScan(basePackages = "com.abc.springboot.mapper")
@EnableTransactionManagement //开启事务支持(可选项,但@Transactional 必须添加)
public class Application {
   ...}

3.3 Spring Boot下的 Spring MVC

Spring Boot 下的 Spring MVC 和之前的 Spring MVC 使用是完全一样的,主要有以下注解

  • @Controller 处理 http 请求
  • @RestController
    如果一个 Controller 类添加了@RestController,那么该 Controller 类下的所有方法都相当
    于添加了@ResponseBody 注解用于返回 字符串或 json 数据
  • @RequestMapping 支持 Get \Post请求
  • @GetMapping 只支持 Get 请求,主要用于查询操作
  • @PostMapping 只支持 Post 请求,主要用户新增数据
  • @PutMapping 只支持 Put 请求,通常用于修改数据
  • @DeleteMapping 只支持 Delete 请求,通常用于删除数据

可以使用 Http 接口请求工具 Postman,模拟发送不同类型的请求

3.4 Spring Boot实现 ResTful

REST(Representational State Transfer)一种互联网软件架构设计的风格
提出了一组客户端和服务器交互时的架构理念和设计原则,
基于这种理念和原则设计的接口可以更简洁,更有层次

要访问一个 http 接口:http://localhost:8080/boot/order?id=1021&status=1
采用 RESTFul 风格则 http 地址为:http://localhost:8080/boot/order/1021/1

Spring boot 开发 RESTFul 主要是几个注解实现

  • @PathVariable 获取 url 中的数据 (最主要)
  • @PostMapping 接收和处理 Post 方式的请求
  • @DeleteMapping 接收 delete 方式的请求,可以使用 GetMapping 代替
  • @PutMapping 接收 put 方式的请求,可以用 PostMapping 代替
  • @GetMapping 接收 get 方式的请求
@RestController
public class RESTfulController {
   
	@PostMapping(value = "/springBoot/student/{name}/{age}")
	public Object addStudent(@PathVariable("name") String name,
		@PathVariable("age") Integer age) {
   
		Map<String,Object> retMap = new HashMap<String, Object>();
		retMap.put("name",name);
		retMap.put("age",age);
		return retMap;
	}
}

RESTful原则
➢ 增 post 请求、删 delete 请求、改 put 请求、查 get 请求
➢ 请求路径不要出现动词
➢ 分页、排序等操作,不需要使用斜杠传参数

3.5 Spring Boot集成Redis

案例思路:
完善根据学生 id 查询学生的功能,先从 redis 缓存中查找,
如果找不到,再从数据库中查找,
然后放到 redis 缓存中

➢在 pom.xml 文件中添加 redis 依赖

<!-- 加载 spring boot redis 包 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

➢核心配置文件

#配置内嵌 Tomcat 端口号
server.port=9090
#配置项目上下文根
server.servlet.context-path=/016-springboot-redis

#配置连接 MySQL 数据库信息
spring.datasource.url=jdbc:mysql://192.168.92.134:3306/springboot?useUnicode
=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDa
tetimeCode=false&serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456

#配置 redis 连接信息
spring.redis.host=192.168.92.134
spring.redis.port=6379
spring.redis.password=123456

➢启动 redis 服务
➢RedisController 类
➢ StudentService 接口
➢在 StudentServiceImpl 中注入 RedisTemplate
并修改根据 id获取学生的方法

@Service
public class StudentServiceImpl implements StudentService {
   
	@Autowired
	private StudentMapper studentMapper;
	@Autowired
	private RedisTemplate<Object,Object> redisTemplate;
	
	@Override
	public Long queryAllStudentCount() {
   
		//设置 redisTemplate 对象 key 的序列化方式
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		
		//从 redis 缓存中获取总人数
		Long allStudentCount = (Long) redisTemplate.opsForValue().get("allStudentCount");
		//判断是否为空
		if (null == allStudentCount) {
   
		//去数据库查询,并存放到 redis 缓存中
		allStudentCount = studentMapper.selectAllStudentCount();
		redisTemplate.opsForValue().set("allStudentCount",allStudentCount,15, 
			TimeUnit.SECONDS);
		}
		return allStudentCount;
} }

➢让 Student 类实现序列化接口

public class Student implements Serializable{
   ...}

3.6 Spring Boot集成Dubbo

阿里dubbo 集 成 springBoot 开 源 项 目

dubbo官方推荐至少需要3个工程
1.接口工程:存放实体类和业务接口
	maven java工程
2.服务提供者:接口的实现类,该工程集成MyBatis和Spring
	MyBatis依赖,MyBatis集成Spring依赖,MySQL驱动,Spring相关依赖,Dubbo依赖,
	注册中心zookeeper依赖,Spring集成redis依赖
	1.添加依赖
	2.配置核心配置文件(数据库配置,redis配置,dubbo配置)
	3.MyBatis逆向工程
	4.接口的实现类
3.服务消费者:处理用户浏览器的请求,该工程集成Spring和SpringMVC
	Spring相关依赖,Dubbo依赖,注册中心zookeeper依赖
	1.添加依赖
	2.配置核心配置文件(dubbo配置,配置视图解析器)
	3.编写控制层处理用户的请求
3.6.1 开发Dubbo服务接口
A、 创建普通 Maven 项目,dubbo 服务接口工程,只定义接口和model类
B、 创建 UserService 接口
3.6.2 开发 Dubbo 服务提供者
A、 创建 SpringBoot 框架的 WEB 项目

B、 加入 Dubbo 集成 SpringBoot 的起步依赖
<dependency>
	 <groupId>com.alibaba.spring.boot</groupId>
	 <artifactId>dubbo-spring-boot-starter</artifactId>
	 <version>2.0.0</version>
</dependency>

C、 由于使用 zookeeper 作为注册中心,需加入 zookeeper 的客户端依赖
<dependency>
	 <groupId>com.101tec</groupId>
	 <artifactId>zkclient</artifactId>
	 <version>0.10</version>
</dependency>

D、 加入 MyBatis 和 MySQL 依赖
<!--MyBatis 集成 SpringBoot 框架起步依赖-->
<dependency>
	 <groupId>org.mybatis.spring.boot</groupId>
	 <artifactId>mybatis-spring-boot-starter</artifactId>
	 <version>2.0.1</version>
</dependency>
<!--MySQL 数据库驱动-->
<dependency>
	 <groupId>mysql</groupId>
	 <artifactId>mysql-connector-java</artifactId>
</dependency>

E、 加入 Dubbo 接口依赖
<dependency>
	 <groupId>com.abc.springboot</groupId>
	 <artifactId>017-springboot-dubbo-interface</artifactId>
	 <version>1.0.0</version>
</dependency>

F、 在 核心配置文件中配置 dubbo
#设置内嵌 Tomcat 端口号
#设置上下文根
#配置数据源

#配置 dubbo 的服务提供者信息
#服务提供者应用名称(必须写,且不能重复)
spring.application.name=springboot-dubbo-provider
#设置当前工程为服务提供者
spring.dubbo.server=true
#设置注册中心
spring.dubbo.registry=zookeeper://localhost:2181

G、编写 Dubbo 的接口实现类
@Component
@Service(interfaceName = 
"com.abc.springboot.service.StudentService",version = "1.0.0",timeout = 15000)
public class StudentServiceImpl implements StudentService {
	@Autowired
	private StudentMapper studentMapper;
	@Override
	public Student queryStudent(Integer id) {
		return studentMapper.selectByPrimaryKey(id);
 } }
 
 H、在 SpringBoot 入口程序类上加开启 Dubbo 配置支持注解
@EnableDubboConfiguration //开启 Dubbo 配置
public class Application {...}

I、 启动 Zookeeper 服务

3.6.3 开发 Dubbo 服务消费者

A、加入 Dubbo 集成 SpringBoot 框架的起步依赖
B、加入 zookeeper 的客户端依赖
C、加入 Dubbo 接口依赖
D、核心配置文件配置Dubbo
#设置内嵌 Tomcat 端口号
#设置上下文根
server.servlet.context-path=/ 

#设置 dubbo 配置
#设置服务消费者名称
spring.application.name=springboot-dubbo-consumer
#配置 dubbo 注册中心
spring.dubbo.registry=zookeeper://localhost:2181

F、编写一个 Controller 类,调用远程的 Dubbo 服务
@RestController
public class StudentController {
	@Reference(interfaceName = 
	"com.abc.springboot.service.StudentService",version = "1.0.0",check = false)
	private StudentService studentService;
	
	@RequestMapping(value = "/student")
	public Object queryStudent(Integer id) {
		Student student = studentService.queryStudent(id);
		return student;
 } }

G、 在 SpringBoot 入口程序类上加开启 Dubbo 配置支持注解
@SpringBootApplication
@EnableDubboConfiguration //开启 Dubbo 配置
public class Application {...}
3.6.4 Spring Boot 集成SSM+Dubbo+Redis

4 Spring Boot 非Web应用程序

4.1 获取返回的 Spring 容器对象,再获取业务 bean 进行调用

@SpringBootApplication
public class Application {
   
	public static void main(String[] args) 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值