一、简介 1.1 spring优缺点 优点
提供了依赖注入 面向切面编程 可选注解或者xml 缺点
spring组件是轻量级的,但是配置却是重量级的。也就是少写了代码,多写了配置 依赖管理也费事费力,如版本问题。 1.2 springboot概述 springboot对spring的优缺点进行了改善和优化。基于约定优于配置 的思想,让开发人员可以只关心逻辑实现,而不用再去为配置耗时。从而提高了开发效率,缩减项目周期。
springboot的特点
为基于spring开发提供更快的入门体验 开箱即用,没有代码生成,也无需xml配置 提供大型项目中常见的非功能特性,如嵌入式服务器(springboot本身内置了tomcat服务器,不需要在打包放到tomcat里面跑)、安全、指标、健康检测(我现在工作就用了健康检测)等 springboot只是提供了快速使用spring的方式 1.3 springboot核心功能 核心功能
起步依赖本质上就是一个Maven项目对象模型(Project Object Model,POM),定义了对其他库的传递依赖,这些东西加在一起即支持某项功能。简单说,起步依赖就是将具备某种功能的坐标打包到一起,并提供一些默认功能 自动配置 二、入门 2.1 快速入门 步骤
创建Maven工程,普通的java工程即可 添加springboot的起步依赖 添加springboot的引导类 创建控制器 就普通的maven工程即可
SpringBoot要求,项目要继承SpringBoot的起步依赖,spring-boot-starter-parent
1 2 3 4 5 6 <parent > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-parent</artifactId > <version > 2.4.5</version > <relativePath /> </parent >
SpringBoot要集成SpringMVC进行Controller开发,所以项目要导入web的启动依赖
1 2 3 4 5 6 <dependencies > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-web</artifactId > </dependency > </dependencies >
总配置文件如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 <?xml version="1.0" encoding="UTF-8"?> <project xmlns ="http://maven.apache.org/POM/4.0.0" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > <modelVersion > 4.0.0</modelVersion > <parent > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-parent</artifactId > <version > 2.4.5</version > <relativePath /> </parent > <groupId > top.meethigher</groupId > <artifactId > SpringBoot</artifactId > <version > 1.0</version > <dependencies > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-web</artifactId > </dependency > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-test</artifactId > <scope > test</scope > </dependency > </dependencies > </project >
添加控制器如下
1 2 3 4 5 6 7 8 @Controller public class QuickController { @RequestMapping ("/quick" ) @ResponseBody public String quick () { return "Hello Spring Boot" ; } }
@Controller和@ResponseBody可以通过@RestController来替换。添加了@RestController就可以不用再写那两个了。
添加引导类
1 2 3 4 5 6 7 @SpringBootApplication public class Start01 { public static void main (String[] args) { SpringApplication.run(Start01.class ) ; } }
访问localhost:8080/quick即可。
2.2 springboot的热部署 首先pom中导入热部署依赖
1 2 3 4 5 <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-devtools</artifactId > </dependency >
其次,idea开启自动编译功能
第一步,设置里面开启自动编译
第二部,ctrl+shift+alt+/找到Registry
2.3 借助idea快速创建springboot工程 用spring初始化这个工具
在下面可以选择自己的依赖,比如热部署的、web开发的。
三、原理 3.1 起步依赖 pom选中要看的依赖,ctrl左键就能看到相应的pom,如果没反应的话,尝试重启idea,或者去maven仓库看一下,到底有没有下载下来
像spring-boot-starter-parent,我们可看他里面的指定配置文件名称等的内容,还可以继续看他的父级spring-boot-dependencies,然后就能看到springboot内置的一些依赖。
这样就算是统一了,不用担心自己导依赖的时候,有版本问题
3.2 自动配置 @SpringBootApplication注解的作用,相当于以下三个
@SpringBootConfiguration:查看源码,可以知道相当于@Configuration,指定当前类是个配置类 @ComponentScan:扫描包 @EnableAutoConfiguration:是否自动配置的开关。源码里面有@Import用于引入其他配置类 通过@EnableAutoConfiguration
我们就可以找到许多自动配置,里面配置了许多默认属性。
如果我们想要更改默认配置,只需要在springboot的配置文件中,添加server.port属性即可。
如果是用的mybatis启动器,那么也可以这么找来配置。
找到mybatis的autoconfigure,然后找到配置json,搜索指定关键字就能找到了。
比如
1 2 server.port =444 server.servlet.context-path =/demo
或者
1 2 3 4 server: port: 8080 servlet: context-path: /demo
四、配置 springboot的配置文件有两种,properties和yml(yaml),下面使用yml来演示
4.1 yml配置文件 yml文件格式是YAML(YAML Aint Markup Language)编写的文件格式,类似于json的格式。
扩展名可以为.yml
或者.yaml
配置普通数据 语法
注意
value之前要带空格
配置对象数据 语法
1 2 3 key: key1: value1 key2: value2
或者
1 key: {key1: value1,key2: value2}
配置集合数据 如果集合中存的是普通数据
1 2 3 4 city: - taian - changchun - wuhan
或者
1 city: [taian,changchun,wuhan]
如果集合中存的是对象数据
1 2 3 4 5 6 7 8 9 10 student: - name: ccc age: 18 addr: taian - name: ccc age: 19 addr: changchun - name: ccc age: 24 addr: wuhan
或者
1 student: [{name:ccc,age:18,addr:taian},{name:ccc,age:19,addr:changchun},{name:ccc,age:24,addr:wuhan}]
相当于存的三个数据,都是一个对象
4.2 获取配置文件内容 两种方式
@Value:适合直接取值 @ConfigurationProperties:适合多个属性的一起取 配置文件
1 2 3 4 5 6 7 8 9 server: port: 8080 servlet: context-path: /demo name: ccc person: name: ccc age: 14 addr: wuhan
@Value的示例
1 2 3 4 5 6 7 8 9 10 11 12 @RestController public class Quick2Controller { @Value ("${name}" ) private String name; @Value ("${person.addr}" ) private String addr; @RequestMapping ("/quick2" ) public String quick2 () { return addr; } }
@ConfigurationProperties的示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 @RestController @ConfigurationProperties (prefix = "person" )public class Quick3Controller { private String name; private String addr; private Integer age; public String getName () { return name; } public void setName (String name) { this .name = name; } public String getAddr () { return addr; } public void setAddr (String addr) { this .addr = addr; } public Integer getAge () { return age; } public void setAge (Integer age) { this .age = age; } @RequestMapping ("/quick3" ) public String quick2 () { return getName()+getAddr()+getAge(); } }
pom中添加@ConfigurationProperties自动提示执行器的依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 <?xml version="1.0" encoding="UTF-8"?> <project xmlns ="http://maven.apache.org/POM/4.0.0" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > <modelVersion > 4.0.0</modelVersion > <parent > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-parent</artifactId > <version > 2.4.5</version > </parent > <groupId > top.meethigher</groupId > <artifactId > SpringBoot</artifactId > <version > 1.0</version > <dependencies > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-web</artifactId > </dependency > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-devtools</artifactId > </dependency > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-configuration-processor</artifactId > <optional > true</optional > </dependency > </dependencies > </project >
五、整合 5.1 springboot整合mybatis 步骤
添加mybatis的起步依赖 添加数据库驱动坐标 添加数据库连接信息 创建表 创建bean 编写Mapper 配置Mapper映射文件 在application.yml添加mybatis 添加控制器 pom如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 <?xml version="1.0" encoding="UTF-8"?> <project xmlns ="http://maven.apache.org/POM/4.0.0" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > <modelVersion > 4.0.0</modelVersion > <parent > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-parent</artifactId > <version > 2.4.5</version > <relativePath /> </parent > <groupId > top.meethigher</groupId > <artifactId > springboot_mybaits</artifactId > <version > 0.0.1-SNAPSHOT</version > <name > springboot_mybaits</name > <description > Demo project for Spring Boot</description > <properties > <java.version > 11</java.version > </properties > <dependencies > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-jdbc</artifactId > </dependency > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-web</artifactId > </dependency > <dependency > <groupId > org.mybatis.spring.boot</groupId > <artifactId > mybatis-spring-boot-starter</artifactId > <version > 2.1.4</version > </dependency > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <scope > runtime</scope > </dependency > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-test</artifactId > <scope > test</scope > </dependency > </dependencies > <build > <plugins > <plugin > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-maven-plugin</artifactId > </plugin > </plugins > </build > </project >
springboot配置
1 2 3 4 5 6 7 8 9 10 spring.datasource.driver-class-name =com.mysql.cj.jdbc.Driver spring.datasource.username =root spring.datasource.password =root spring.datasource.url =jdbc:mysql://localhost:3306/springboot?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai mybatis.type-aliases-package =top.meethigher.springboot_mybaits.domain mybatis.mapper-locations =classpath:mapper/*Mapper.xml
实体类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 public class Account { private Integer id; private String name; private Float money; public Integer getId () { return id; } public void setId (Integer id) { this .id = id; } public String getName () { return name; } public void setName (String name) { this .name = name; } public Float getMoney () { return money; } public void setMoney (Float money) { this .money = money; } @Override public String toString () { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", money=" + money + '}' ; } }
Mapper
1 2 3 4 @Mapper public interface AccountMapper { List<Account> findAll () ; }
控制器
1 2 3 4 5 6 7 8 9 10 @RestController public class AccountController { @Autowired private AccountMapper accountMapper; @RequestMapping ("/findAll" ) public List<Account> findAll () { List<Account> all = accountMapper.findAll(); return all; } }
5.2 springboot整合junit 导入junit的起步依赖。因为springboot2.4.5使用的是junit5.7.1,所以跟4有点不同。
测试类这么写
1 2 3 4 5 6 7 8 9 10 11 @SpringBootTest public class MybatisTest { @Autowired private AccountMapper accountMapper; @Test void testFindAll () { System.out.println(accountMapper.findAll()); } }
5.3 springboot整合jpa pom
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 <?xml version="1.0" encoding="UTF-8"?> <project xmlns ="http://maven.apache.org/POM/4.0.0" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > <modelVersion > 4.0.0</modelVersion > <parent > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-parent</artifactId > <version > 2.4.5</version > <relativePath /> </parent > <groupId > top.meethigher</groupId > <artifactId > springboot_jpa</artifactId > <version > 0.0.1-SNAPSHOT</version > <name > springboot_jpa</name > <description > Demo project for Spring Boot</description > <properties > <java.version > 11</java.version > </properties > <dependencies > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-data-jpa</artifactId > </dependency > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-jdbc</artifactId > </dependency > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-web</artifactId > </dependency > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <scope > runtime</scope > </dependency > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-test</artifactId > <scope > test</scope > </dependency > </dependencies > <build > <plugins > <plugin > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-maven-plugin</artifactId > </plugin > </plugins > </build > </project >
实体类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 @Entity @Table (name="person" )public class Person { @Id @GeneratedValue (strategy = GenerationType.IDENTITY) private Integer uId; private String uName; private Integer uAge; private String uAddr; public Integer getuId () { return uId; } public void setuId (Integer uId) { this .uId = uId; } public String getuName () { return uName; } public void setuName (String uName) { this .uName = uName; } public Integer getuAge () { return uAge; } public void setuAge (Integer uAge) { this .uAge = uAge; } public String getuAddr () { return uAddr; } public void setuAddr (String uAddr) { this .uAddr = uAddr; } @Override public String toString () { return "Person{" + "uId=" + uId + ", uName='" + uName + '\'' + ", uAge=" + uAge + ", uAddr='" + uAddr + '\'' + '}' ; } }
接口
1 2 public interface PersonRepository extends JpaRepository <Person ,Integer > {}
springboot配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 spring.datasource.driver-class-name =com.mysql.cj.jdbc.Driver spring.datasource.username =root spring.datasource.password =root spring.datasource.url =jdbc:mysql://localhost:3306/springboot?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai spring.jpa.database =mysql spring.jpa.hibernate.ddl-auto =update spring.jpa.show-sql =true spring.jpa.generate-ddl =true spring.jpa.hibernate.naming.physical-strategy =org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
测试类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 @SpringBootTest class SpringbootJpaApplicationTests { @Autowired PersonRepository personRepository; @Test void contextLoads () { Person person = new Person(); person.setuName("hh" ); person.setuAge(10 ); person.setuAddr("武汉" ); personRepository.save(person); List<Person> all = personRepository.findAll(); System.out.println(all); } }
5.4 springboot整合Redis pom
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 <?xml version="1.0" encoding="UTF-8"?> <project xmlns ="http://maven.apache.org/POM/4.0.0" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > <modelVersion > 4.0.0</modelVersion > <parent > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-parent</artifactId > <version > 2.4.5</version > <relativePath /> </parent > <groupId > top.meethigher</groupId > <artifactId > springboot_redis</artifactId > <version > 0.0.1-SNAPSHOT</version > <name > springboot_redis</name > <description > Demo project for Spring Boot</description > <properties > <java.version > 11</java.version > </properties > <dependencies > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-data-redis</artifactId > </dependency > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-web</artifactId > </dependency > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-test</artifactId > <scope > test</scope > </dependency > </dependencies > <build > <plugins > <plugin > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-maven-plugin</artifactId > <configuration > <excludes > <exclude > <groupId > org.projectlombok</groupId > <artifactId > lombok</artifactId > </exclude > </excludes > </configuration > </plugin > </plugins > </build > </project >
springboot配置
1 2 spring.redis.host =127.0.0.1 spring.redis.port =6379
测试类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 @SpringBootTest class SpringbootRedisApplicationTests { @Autowired private RedisTemplate<String,String> redis; @Test void contextLoads () { String s = redis.boundValueOps("user.findAll" ).get(); if (s==null ){ redis.boundValueOps("user.findAll" ).set("哈哈哈哈" ); } System.out.println(s); } }
六、实用功能 6.1 发送邮件 导入依赖
1 2 3 4 <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-mail</artifactId > </dependency >
application.yml
1 2 3 4 5 6 7 spring: mail: port: 80 host: smtp.mxhichina.com username: admin password: admin protocol: smtp
发送邮件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 @SpringBootTest class DemoApplicationTests { @Autowired JavaMailSender javaMailSender; @Value ("${spring.mail.username}" ) private String from; @Test void contextLoads () { SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); simpleMailMessage.setSubject("小狂神你好呀" ); simpleMailMessage.setText("halo wode" ); simpleMailMessage.setTo("24736743@qq.com" ); simpleMailMessage.setFrom(from); javaMailSender.send(simpleMailMessage); } @Test void contextLoads2 () throws MessagingException { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true ); mimeMessageHelper.setSubject("小狂神你好呀" ); mimeMessageHelper.setText("halo wode" ); mimeMessageHelper.addAttachment("1.jpg" , new File("src/main/resources/static/壁纸14.jpg" )); mimeMessageHelper.setTo("24736743@qq.com" ); mimeMessageHelper.setFrom(from); javaMailSender.send(mimeMessage); } }
注意
如果想发送html邮件,需要注意应该用的是复杂邮件,并设置响应类型为text/html
6.2 定时任务 springboot中提供的定时任务有两种
TaskExecutor:任务执行 TaskScheduler:任务调度@EnableScheduling:开启定时功能的注解,一般是在启动类 @Scheduled:表示什么时候执行,给要执行的方法添加即可 cron表达式
秒:0-59,0/5表示每5秒 分:0-59 时:0-23 日:0-31 月:0-11 周几:0-7,其中0和7都表示周日 cron表达式在线解析
1 2 3 4 5 6 7 8 @Service public class ScheduledService { private Logger log= LoggerFactory.getLogger(ScheduledService.class ) ; @Scheduled (cron = "0 * * * * *" ) public void hello () { log.info("halo wode" ); } }
6.3 异步执行 这个可以与前端的ajax类似。
启动类@EnableAsync,开启异步
想要异步执行的方法上加@Async
七、一些坑 获取配置文件内容 在properties配置文件中,中文读取会乱码,中文需要设置成unicode编码
给内部类中属性赋值,内部类需要用static修饰,具体原因不明
application.properties
1 2 kafka-topic.topic.task-monitor =task-monitor-topic
KafkaTopic.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 @Configuration @ConfigurationProperties (prefix = "kafka-topic" )public class KafkaTopic { private TopicName topic; static class TopicName { private String taskMonitor; public String getTaskMonitor () { return taskMonitor; } public void setTaskMonitor (String taskMonitor) { this .taskMonitor = taskMonitor; } } public TopicName getTopic () { return topic; } public void setTopic (TopicName topic) { this .topic = topic; } }