Spring Boot
一. Spring Boot基本框架
Model层
存放实体类,与数据库字段保持一致:成员变量+getter/setter方法实现字段映射为属性
Mapper层
数据库CRUD接口,只有方法名,封装了对数据库的持久化操作,具体sql语句在mapper.xml或接口注解里实现
service层
存放业务处理逻辑,service的impl是把Mapper和service接口进行整合的文件
接口:声明方法
继承实现接口
impl:接口实现
controller层
响应用户请求:决定使用什么视图,需要准备什么数据用来显示
View层
视图根据接到的数据最终展示页面给用户浏览
用户
数据库
二. Spring Boot整合Mybatis
1. 增加依赖:
pom文件引入 mybatis 依赖和 mysql 驱动
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector}</version> </dependency>
2. 在 yml 配置文件中配置数据源和要扫描加载的 mapper 映射文件:
配置Datasource和实现 mapper 映射
# Spring配置 Spring: datasource: url: jdbc:mysql://119.3.199.81:3366/neuq_examples?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false # 连接数据库用户名 username: example # 连接数据库密码 password: neuq168168 # 设置驱动 driver-class-name: com.mysql.cj.jdbc.Driver # 连接池设置 type: com.alibaba.druid.pool.DruidDataSource # 初始化时建立物理连接的个数 initialSize: 10 # 最大连接池数量 maxActive: 50 # 最小连接池数量 minIdle: 10 # MyBatis配置 mybatis: # 搜索指定包别名 typeAliasesPackage: cn.codnoy.springboot.examples.model # 配置mapper的扫描,找到所有的mapper.xml映射文件 mapperLocations: classpath*:mapper/**/*Mapper.xml # 加载全局的配置文件 configLocation: classpath:mybatis/mybatis-config.xml
3. 新建mapper(以下为注解形式的sql语句)
也可以新建
mapper.xml
写sql
语句前提是具备model中属性和字段的对应
@Mapper public interface UserMapper { @Insert("insert into t1 values(1,1,1,1,'1')") void insert(); @Select("select a from t1 limit 1") String select(); }
4. mapper注入service层再通过controller实现操作数据库
@Component public class UserService { private static Log log = LogFactory.getLog(UserService.class); @Autowired private UserMapper userMapper; public void test() { userMapper.insert(); String result = userMapper.select(); log.info(result); } }
@MapperScan
可以不使⽤@Mapper注解,在主启动类可以通过@MapperScan来进⾏扫描
@SpringBootApplication @MapperScan public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
三. Spring Boot的第一个Hello world
0. 环境配置和创建Maven项目
0.1 选择jdk
,Maven的archetype
,并输入【GroupId】、【ArtifactID】、【Version】等信息
0.2 在【Editor】->【File Encodings】中
-
设置编码格式,三处全部设置成UTF-8
-
-
Global Encoding
-
Project Encoding
-
Default Encoding for properties file
-
0.3 点击【Project Structure】查看SDK是否是自己用的版本(11),之后按【OK】按钮,完成设置
1. 修改Maven配置
1.1 定义jar包的版本(在【properties】节点添加SpringBoot的版本信息):
<properties> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> <!-- spring-boot version --> <spring-boot.version>2.7.2</spring-boot.version> </properties>
1.2 添加SpringBoot依赖(开发web应⽤的starter依赖)
因为我们创建的是⼀个Web⼯程,从⽇志中,我们可以发现Spring Boot默认使⽤了Tomcat,并绑定了 8080端⼝。
此时打开浏览器访问
localhost:8080/hello
,就可以访问到我们在上⾯所定义的controller,注意配置的路径 为“/hello”,所以直接通过localhost:8080/hello
就可以访问home⽅法。
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
2. 修改启动类
package com.cloudSpring; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main( String[] args ) { SpringApplication.run(App.class, args); } }
3. 添加接口
package com.cloudSpring.controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/hello") public String viewHomePage(Model model) { return "欢迎跟老码农一起学SpringCloud, 期待你的加入!"; } }
四. Spring Boot中的Starters
-
基本概念
-
每个 starter 实质就是⼀个pom.xml⽂件
-
命名规范:Spring Boot官⽅虽然提供了很多starter,但是有时可能仍然需要第三⽅来来⾃⼰实现 ⼀个starter并提供出来,对于这种情况,Spring Boot是有规范的,Spring Boot官⽅默认提供的starter 命名格式为
spring-boot-starter-*
,第三⽅⾃⼰实现的starter的命名格式为*-spring-boot -starter
-
版本指定
-
由
<parent>
父标签控制,根源是spring-boot-dependencies
中的IDEA自定版本
<parent> <artifactId>cloudsky</artifactId> <groupId>org.example</groupId> <version>1.0-SNAPSHOT</version> </parent>
-
Maven会先从本地仓库根据groupId和artifactId看是否有匹配的Jar包,如果没有就会进⾏下载
-
相关依赖
⼀个Spring Boot的web⼯程:正常来说,搭建⼀个web⼯程,是 要依赖很多东⻄的,⽐如tomcat,spring-web,spring-webmvc等等依赖,spring-boot-starter-web的作⽤就是帮我们提前把我们要开发⼀个web应用的依赖都写好了,我们只要依赖spring-boot-starter-web,就相当于了依赖其他很多相关的依赖。
五. Spring Boot中的配置类
在Spring Boot中,我们可以使用XML的方式来对Spring进⾏配置,也可以通过Java Config(也就是类+注解)的方式进⾏配置。
-
可以通过@ImportResource注解来导⼊⼀个XML⽂件作为Spring的配置⽂件来定义Bean
-
主启动类
@EnableAutoConfiguration @ImportResource("spring.xml") public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
-
spring.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="userService" class="com.zhouyu.service.UserService" /> <bean id="userController" class="com.zhouyu.controller.UserController" /> </beans>
-
controller
@RestController public class UserController { @Autowired private UserService userService; @RequestMapping("/") String home() { return userService.test(); } }
-
service
public class UserService { public String test() { return "hello world"; } }
-
可以通过@Import+@Configuration+@Bean来进⾏等价替换掉XML的形式
-
配置类AppConfig
@Configuration public class AppConfig { @Bean public UserService userService(){ return new UserService(); } @Bean public UserController userController(){ return new UserController(); } }
-
主启动类
@Import(AppConfig.class) @EnableAutoConfiguration public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
-
可以直接让MyApplication成为⼀个配置类,这样就不⽤额外添加⼀个AppConfig类
@EnableAutoConfiguration @Configuration public class MyApplication { @Bean public UserService userService(){ return new UserService(); } @Bean public UserController userController(){ return new UserController(); } public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
-
配置类的作⽤除开可以通过@Bean来定义Bean之外,也可以配置扫描路径
@EnableAutoConfiguration @Configuration @ComponentScan("org.example") public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
这样就不需要⽤@Bean了,但是得在类上加上@Component注解来定义Bean
扫描过程中,除开可以扫描到@Component、@Service、@Controller、@RestController等注解之 外,也能扫描到@Configuration。
也就是可以在扫描路径下定义其他的配置类。
-
由于MyApplication类所在包就是org.example,所以可以直接这么写
@EnableAutoConfiguration @Configuration @ComponentScan public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
此时扫描路径就是@ComponentScan注解所在的类的包路径
此时MyApplication就存在三个注解: @EnableAutoConfiguration @Configuration @ComponentScan
在Spring Boot中,提供了⼀个注解来替代这三个注解,这个注解就是@SpringBootApplication
最终简化为如下:
@SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
定义了MyApplication类是⼀个配置类
定义了扫描路径,就是MyApplication所在的包路径
加了@EnableAutoConfiguration,开启⾃动配置
六. Spring Boot中的自动配置
-
Spring Boot自动配置会根据项目中所添加的依赖进行自动配置,比如项目中添加了
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
-
而这个依赖中,间接添加了
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>3.0.0-M1</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <version>3.0.0-M1</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>6.0.0-M2</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>6.0.0-M2</version> <scope>compile</scope> </dependency>
在搭建Spring MVC⼯程时,除开要假如spring-web,spring-webmvc等依赖包之外, 最复杂的就是还要进⾏很多额外的配置
Spring Boot中:
项目中引⼊的spring-boot-starter-web中,而这个里面又引入了spring-boot-autoconfigure
在spring-boot-autoconfigure依赖中存在一个⽂件spring.factories,这个⽂件中记录了很多的 AutoConfiguration类,这些⾃动配置类(其实就是配置类)就是用来进行自动配置的。
只有加了@EnableAutoConfiguration注解,spring.factories⽂件中所记录的⾃动配置类才会⽣效,因为 @EnableAutoConfiguration注解会去寻找spring.factories⽂件,并解析内容,所以能解析出来自动配置类,并进⼀步对配置类进⾏解析。
比如在spring.factories文件中存在⼀个DispatcherServletAutoConfiguration,是⽤来对 DispatcherServlet进行自动配置
自动配置并不是去帮助我们配置扫描路径之类的,是针对各种各样的场景,Spring Boot已经给我们配置好了本来是我们需要配置的⼀些Bean以及⼀些参数。
七. Spring Boot中的属性绑定
我们可以使用@Value("${sss}")的⽅式来获取properties中的属性值。
如果properties文件的名字是application.properties,那就不需要用@PropertySource注解,如果不是,就需要@PropertySource("hello.properties")
在Spring Boot提供了⼀种更方便的方式来获取properties文件中的属性值。
比如我们用@Value,在UserService得写⼀遍所有的@Value,可能在其他Service也得写⼀遍
@Component public class UserService { @Value("${username}") private String username; @Value("${password}") private String password; public String test() { return username + ":" + password; } }
-
⽤Spring Boot,可以自定义一个MyProperties
@ConfigurationProperties @Component public class MyProperties { private String username; private String password; // setter getter }
-
然后,在UserService中,把MyProperties当作一个Bean⽤即可
@Component public class UserService { @Autowired private MyProperties myProperties; public String test() { return myProperties.getUsername() + ":" + myProperties.getPassword(); } }
另外还可以使用@ConfigurationPropertiesScan来进行扫描,这样,MyProperties也可以生效。
@SpringBootApplication @ConfigurationPropertiesScan("org.example.service") public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
有时,如果我们想利用我们自己的properties来构造第三⽅提供的Bean,那就可以利⽤ @Bean+@ConfigurationProperties
八. Spring Boot中的外部配置
Spring Boot虽然会⾃动给我们做⼀些配置,有些配置是自己来配,比如数据库的连接地址,用户名,密码等。 我们可以通过Java properties files, YAML files, environment variables, and command-line arguments来进行配置。
-
命令行参数 > VM环境变量优先级 > 操作系统环境变量 > application.properties > application.yml
例如:
-
application.properties中配置
password: neuq168168
-
UserService类可以得到
@Component @ConfigurationProperties public class UserService { private String password; public String test() { return password; } }
九. Spring Boot中常见条件注解
在自动配置类中,通常能看到很多条件注解(比如@ConditionalOnClass、@ConditionalOnBean), 这是因为,如果我们要用Spring Boot的自动配置功能,就会加上@EnableAutoConfiguration注解,从而就会将解析spring.factories文件中的所有自动配置类.
但是在⼀个项目中并不是所有自动配置类都要使用到。 比如不需要用到MVC,那么WebMvcAutoConfiguration就没什么用,没用的配置类,就希望不要让Spring去解析它。
例如:
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
-
表示只有Spring容器中没有WebMvcConfigurationSupport.class类型的Bean时,WebMvcAutoConfiguration才生效
-
ConditionalOnBean:是否存在某个某类或某个名字的Bean
-
ConditionalOnMissingBean:是否缺失某个某类或某个名字的Bean
-
ConditionalOnSingleCandidate:是否符合指定类型的Bean只有⼀个 (注意运行顺序)
-
ConditionalOnClass:是否存在某个类
-
ConditionalOnMissingClass:是否缺失某个类
-
ConditionalOnExpression:指定的表达式返回的是true还是false
-
ConditionalOnJava:判断Java版本
-
ConditionalOnWebApplication:当前应⽤是⼀个Web应用
-
ConditionalOnNotWebApplication:当前应⽤不是⼀个Web应用
-
ConditionalOnProperty:Environment中是否存在某个属性
参考资料
-
概念
Java---三层架构 MVC SpringBoot基本框架
三层架构、MVC、SpringMVC + Spring + MyBatis 关系
-
应用
-
附录图