SpringBoot
是由 Pivotal
团队提供的全新框架。Spring
应用的初始搭建以及开发过程。Spring Initializr URL:https://start.spring.io
换成https://start.aliyun.com/速度会更快。
注意:打包方式这里需要设置为
Jar
创建好的项目会自动生成其他的一些文件,而这些文件目前对我们来说没有任何作用,所以可以将这些文件删除。
可以删除的目录和文件如下:
.mvn
.gitignore
HELP.md
mvnw
mvnw.cmd
package com.chuhe.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/books")
public class BookController {
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println(id);
return "Hello,spring boot!";
}
}
运行 SpringBoot
工程不需要使用本地的 Tomcat
和 插件,只运行项目 SpringbootQuickstartApplication
类,可以在控制台看出如下信息:
官网地址:https://spring.io/projects/spring-boot
Tomcat
和 Idea
,在自己电脑上启动后端程序,这显然不现实。SpringBoot
工程打成 jar
包,该 jar
包运行不依赖于 Tomcat
和 Idea
这些工具也可以正常运行,只是这个 jar
包在运行过程中连接和程序相同的 Mysql
数据库即可。在构建 SpringBoot
工程时已经在 pom.xml
中配置了如下插件
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
只需要使用 Maven
的 package
指令打包就会在 target
目录下生成对应的 Jar
包。
注意:该插件必须配置,不然打好的
jar
包也是有问题的。
E:\Java\spring\springboot_quickstart\target
下找到打好的jar
包,并运行如下指令
java jar -jar springboot_quickstart-0.0.1-SNAPSHOT.jar
启动工程使用的是tomcat
服务器,能不能不使用tomcat
而使用jetty
服务器?
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-tomcatartifactId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jettyartifactId>
dependency>
启动后发现,tomcat
已换成了jetty
实际开发
使用任意坐标时,仅书写GAV中的G和A,V由SpringBoot提供
G:groupid
A:artifactId
V:version
如发生坐标错误,再指定version(要小心版本冲突)
方式一:application.properties
server.port=80
方式二:application.yml
server:
port: 80
方式三:application.yaml
server:
port: 80
注意: 在
:
后,数据前一定要加空格。
2.7.0开始已经自动变成配置文件了,一般都有语法提示。
application.yml
或application.yaml
如果没有语法提示,可进行如下操作解决:
三种配置文件的优先级是:
application.properties
> application.yml
> application.yaml
注意:
SpringBoot
核心配置文件名为application
SpringBoot
内置属性过多,且所有属性集中在一起修改,在使用时,通过提示键+关键字修改属性例如要设置日志的级别时,可以在配置文件中书写
logging
,就会提示出来。配置内容如下
logging:
level:
root: warn
com: info
YAML(YAML Ain’t Markup Language),一种数据序列化格式。 这种格式的配置文件在近些年已经占有主导地位。
三种常见配置文件格式:
xml
,格式如下:
<enterprise>
<name>唐青枫name>
<age>20age>
<tel>13100000001tel>
enterprise>
properties
类型的配置文件如下
enterprise.name=唐青枫
enterprise.age=20
enterprise.tel=13100000001
yaml
类型的配置文件内容如下
enterprise:
name: itcast
age: 16
tel: 4006184000
大小写敏感。
属性层级关系使用多行描述,每行结尾使用冒号结束。
使用缩进表示层级关系,同层级左侧对齐,只允许使用空格(不允许使用Tab键)。
空格的个数并不重要,只要保证同层级的左侧对齐即可。
属性值前面添加空格(属性名与属性值之间使用冒号+空格作为分隔)。
# 表示注释。
核心规则:数据前面要加空格与冒号隔开。
数组数据在数据书写位置的下方使用减号作为数据开始符号,每行书写一个数据,减号与数据间空格分隔,例如
enterprise:
name: 唐青枫
age: 20
tel: 13100000001
subject:
- Java
- 前端
- 大数据
lesson: SpringBoot
server:
port: 80
enterprise:
name: 唐青枫
age: 20
tel: 13100000001
subject:
- Java
- C++
- Python
方式一:
@RestController
@RequestMapping("/books")
public class BookController {
@Value("${lesson}")
private String lesson;
@Value("${server.port}")
private int port;
@Value("${enterprise.subject[0]}")
private String subject;
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println(lesson);
System.out.println(port);
System.out.println(subject);
return "Hello,spring boot!";
}
}
方式二:Environment对象
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private Environment env;
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println(env.getProperty("lesson"));
System.out.println(env.getProperty("server.port"));
System.out.println(env.getProperty("enterprise.subject[0]"));
return "Hello,spring boot!";
}
}
注意:这种方式,配置文件内有大量数据,在开发中我们很少使用。
方式三:自定义对象
com.chuhe.domain
下定义Enterprise
实体类
package com.chuhe.domain;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
@ConfigurationProperties(prefix = "enterprise")
public class Enterprise {
private String name;
private int age;
//tel如果定义成int,application.yml文件中该字段如果写11位数字会报错,
//因位超过了Int的范围
private String tel;
private String[] subject;
//getter、setter方法略
}
BookControler中读取
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private Enterprise ent;
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println(ent);
return "Hello,spring boot!";
}
}
使用第三种方式,在实体类上有如下警告提示
这个警告提示解决是在
pom.xml
中添加如下依赖即可<dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-configuration-processorartifactId> <optional>trueoptional> dependency> ```
在 application.yml
中使用 ---
来分割不同的配置,内容如下
#设置启用的环境
spring:
profiles:
active: dev
#开发
spring:
profiles: dev #给开发环境起的名字
server:
port: 80
---
#生产
spring:
profiles: pro #给生产环境起的名字
server:
port: 81
---
#测试
spring:
profiles: test #给测试环境起的名字
server:
port: 82
---
注意:
- 在上面配置中给不同配置起名字的
spring.profiles
配置项已经过时。- 最新用来起名字的配置项如下:
#开发 spring: config: activate: on-profile: dev
✈properties
类型的配置文件配置多环境需要定义不同的配置文件
application-dev.properties
是开发环境的配置文件。我们在该文件中配置端口号为 80
server.port=80
application-test.properties
是开发环境的配置文件。我们在该文件中配置端口号为 81
server.port=81
application-pro.properties
是生产环境的配置文件。我们在该文件中配置端口号为 82
server.port=82
SpringBoot
只会默认加载名为 application.properties
的配置文件,所以需要在 application.properties
配置文件中设置启用哪个配置文件,配置如下:
spring.profiles.active=pro
使用 SpringBoot
开发的程序以后都是打成 jar
包,通过 java -jar xxx.jar
的方式启动服务。
配置文件已经打到jar包里了,如何切换环境呢。
SpringBoot
提供了在运行 jar
时设置开启指定的环境的方式,如下:
java –jar xxx.jar --spring.profiles.active=test
临时修改端口号
java –jar xxx.jar --server.port=88
同时设置多个配置,比如即指定启用哪个环境配置,又临时指定端口,如下
java –jar springboot.jar –-server.port=88 –-spring.profiles.active=test
测试后就会发现命令行设置的端口号优先级高(也就是使用的是命令行设置的端口号)。配置的优先级 SpringBoot
官网已经进行了说明,参见:https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config
Maven和SpringBoot中同时设置环境,应该以Maven中配置的环境启动。
步骤一:pom.xml中,设置启动的是test环境
<profiles>
<profile>
<id>devid>
<properties>properties>
profile>
<profile>
<id>testid>
<properties>properties>
<activation>
<activeByDefault>trueactiveByDefault>
activation>
profile>
profiles>
步骤二:application.yma中,设置启动的是dev环境
# 启用开发环境
spring:
profiles:
active: dev
---
#开发环境
Spring:
profiles: dev
server:
port: 80
---
#测试环境
Spring:
profiles: test
server:
port: 81
dev
属性<profiles>
<profile>
<id>devid>
<properties>
<profile.active>devprofile.active>
properties>
profile>
<profile>
<id>testid>
<properties>
<profile.active>devprofile.active>
properties>
<activation>
<activeByDefault>trueactiveByDefault>
activation>
profile>
profiles>
${profile.active}
# 启用开发环境
spring:
profiles:
active: ${profile.active}
---
#开发环境
Spring:
profiles: dev
server:
port: 80
---
#测试环境
Spring:
profiles: test
server:
port: 81
原因:
解决方法:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-resources-pluginartifactId>
<version>2.6version>
plugin>
plugins>
build>
这样启动时就会按照Maven中设置的环境启动了。
开发完毕后需要测试人员进行测试,由于测试环境和开发环境的很多配置都不相同,所以测试人员在运行工程时需要临时修改很多配置,如下:
java –jar springboot.jar –-spring.profiles.active=test --server.port=85 --server.servlet.context-path=/heima --server.tomcat.connection-timeout=-1 …… …… …… …… ……
针对这种情况,SpringBoot
定义了配置文件不同的放置的位置;而放在不同位置的优先级时不同的。
SpringBoot
中4级配置文件放置位置:说明:
注意:
- SpringBoot 2.5.0版本存在一个bug,我们在使用这个版本时,需要在
jar
所在位置的config
目录下创建一个任意名称的文件夹。- 2.4.6版本中也存在这个bug.
Spring
整合 junit
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {
@Autowired
private BookService bookService;
@Test
public void testSave(){
bookService.save();
}
}
✈ 使用 @RunWith
注解指定运行器,使用 @ContextConfiguration
注解来指定配置类或者配置文件。
✈ 而 SpringBoot
整合 junit
特别简单,分为以下三步完成
@SpringBootTest
注解。@Autowired
注入要测试的资源。✈步骤二:com.chuhe.service下增加BookService接口
package com.chuhe.service;
public interface BookService {
public void save();
}
✈步骤三:com.chuhe.service.impl下增加实现类
import com.chuhe.service.BookService;
import org.springframework.stereotype.Service;
@Service
public class BookServiceImpl implements BookService {
@Override
public void save() {
System.out.println("book service is running...");
}
}
✈步骤四:测试类
package com.chuhe;
import com.chuhe.service.BookService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringbootTestApplicationTests {
@Autowired
private BookService bookService;
@Test
public void save() {
bookService.save();
}
}
注意:
这里的引导类所在包必须是测试类所在包及其子包。 例如:
- 引导类所在包是
com.chuhe
- 测试类所在包是
com.chuhe
- 如果不满足这个要求的话,就需要在使用
@SpringBootTest
注解时,使用classes
属性指定引导类的字节码对象。如@SpringBootTest(classes = Springboot07TestApplication.class)
Spring
整合 Mybatis
需要定义很多配置类
SpringConfig
配置类
导入 JdbcConfig
配置类
导入 MybatisConfig
配置类
@Configuration
@ComponentScan("com.itheima")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MyBatisConfig.class})
public class SpringConfig {
}
JdbcConfig
配置类
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String userName;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource getDataSource(){
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(userName);
ds.setPassword(password);
return ds;
}
}
MybatisConfig
配置类
定义 SqlSessionFactoryBean
定义映射配置
@Bean
public MapperScannerConfigurer getMapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("com.itheima.dao");
return msc;
}
@Bean
public SqlSessionFactoryBean getSqlSessionFactoryBean(DataSource dataSource){
SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
ssfb.setTypeAliasesPackage("com.itheima.domain");
ssfb.setDataSource(dataSource);
return ssfb;
}
✈步骤一:创建项目
选择当前模块需要使用的技术集(MyBatis、MySQL)
✈步骤二:创建Book实体类
package com.chuhe.domain;
public class Book {
private Integer id;
private String name;
private String type;
private String description;
//getter和setter省略...
}
✈步骤三:com.chuhe.dao下创建BookDao接口
@Mapper
public interface BookDao {
@Select("select * from tbl_book where id=#{id}")
public Book getById(Integer id);
}
@Mapper
不加会报如下错误
✈步骤四:application.yml配置文件中写入参数
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
username: root
password: "1234"
注意:
SpringBoot
版本低于2.4.3(不含),Mysql驱动版本大于8.0时,需要在url连接串中配置时区
jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
,或在MySQL数据库端配置时区解决此问题- 密码如果是纯数字,需要加引号。
✈步骤五:测试类中测试
@SpringBootTest
class SpringbootMybatisApplicationTests {
@Autowired
private BookDao bookDao;
@Test
void contextLoads() {
Book book=bookDao.getById(1);
System.out.println(book);
}
}
✈步骤一:导入Druid依赖
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.12version>
dependency>
✈步骤二:通过 spring.datasource.type
来配置使用什么数据源。
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
username: root
password: "1234"
type: com.alibaba.druid.pool.DruidDataSource