Springboot

springboot和springMVC区别

image.png

概念:是Spring的子项目,主要简化Sring开发难度,去掉了繁重配置,提供各种启动器,可以让程序员很快上手,节省开发时间。
优点:SpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的
初始搭建
以及开发过程
其他特点:
image.png

  • Spring程序缺点
    • 配置繁琐
    • 依赖设置繁琐
  • SpringBoot程序优点
    • 自动配置
    • 起步依赖(简化依赖配置)
    • 辅助功能(内置服务器,……)

image.png

1.创建

①:创建新模块,选择Spring初始化,并配置模块相关基础信息
image.png

②:选择当前模块需要使用的技术集
SSM等web项目:Web->Spring web、
mybatis项目:SQL->Mysql、SQL->mybatis

image.png
③启动类配置文件等
启动类:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

注意:
controller等文件需要放置在启动类所在目录下
如果不放在一起,启动类上面需要使用@ComponentScan扫包

**pom文件:**见2
④:开发控制器类

@RestController
@RequestMapping("/books")
public class BookController {
    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id) {
        System.out.println("id ==> " + id);
        return "hello , spring boot! ";
    }
}

⑤:运行自动生成的Application类
image.png

2.pom文件

<?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.7.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    
    <groupId>com.itheima</groupId>
    <artifactId>springboot_practice2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <!--下面两行可以删除-->
    <name>springboot_practice2</name>
    <description>springboot_practice2</description>
    
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!-- -->
        <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.2.2</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>
        <!-- -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
		<!--fat打包插件, 使得jar包可以是完整可以运行的 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

**starter:**SpringBoot中常见项目名称,定义了当前项目使用的所有项目坐标,以达到减少依赖配置的目的
**spring-boot-starter-parent:**配置的是一些插件版本锁定。其继承spring-boot-dependencies(定义了坐标版本属性、依赖版本锁定、插件版本锁定)
spring-boot-starter-web:web开发用的起步依赖,里面有spring-web、spring-webmvc、spring-boot-staryer-tomcat(又是一个起步依赖)等依赖
spring-boot-starter-test:测试用的起步依赖,有spring-boot-starter、spring-boot-test、spring-boot-test-autoconfigure、spring-test
spring-boot-configuration-processor:自定义对象封装数据警告解决方案
plugin:
spring-boot-maven-plugin:jar支持命令行启动需要依赖maven插件支持,请确认打包时是否具有SpringBoot对应的maven插件。

3.配置文件

  1. application.properties
  2. application.yml
  3. application.yaml

加载顺序:application.properties > application.yml > application.yaml
YAML(YAML Ain’t Markup Language),一种数据序列化格式

  • 优点:

  • 容易阅读

  • 容易与脚本语言交互

  • 以数据为核心,重数据轻格式

  • YAML文件扩展名

  • .yml(主流)

  • .yaml

  • 语法规则

    • 大小写敏感
    • 属性层级关系使用多行描述,每行结尾使用冒号结束
    • 使用缩进表示层级关系,同层级左侧对齐,只允许使用空格(不允许使用Tab键)
    • 属性值前面添加空格(属性名与属性值之间使用冒号+空格作为分隔)
    • #表示注释
    • 核心规则:数据前面要加空格与冒号隔开
  • 数组数据
    image.png

  • 数据读取

    • 使用@Value读取单个数据,属性名引用方式:${一级属性名.二级属性名……}
      image.png
    • 封装全部数据到Environment对象
      image.png
    • 自定义对象封装指定数据
      image.png
    • 自定义对象封装数据警告解决方案
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

使用Spring的依赖注入,添加一个配置类
image.pngimage.png

注意:
如果使用自定义对象封装指定数据,需要添加@Component将其添加到容器中,或者可以在启动类上添加@EnableConfigurationProperties({MinIOConfigProperties.class})保证这个属性类与javabean的绑定

4.多环境开发配置

注意:

  1. 文件名必须是application
  2. yml和yaml都一样,通常用yml
  3. 打包前先清理clean
  4. idea编码都要是utf-8
  5. 备份的文件夹名叫bak
  6. 后续可能使用yml但是分文件配置的方式,也就是将不同的环境类似于properties的方式,放在不同的文件里,在一个总的配置文件里面进行选择。
yaml、yml配置

image.png
image.png

企业中常用:
image.png

application.properties配置

image.png

Maven与SpringBoot多环境兼容

①:Maven中设置多环境属性

<profiles>
    <profile>
        <id>dev_env</id>
        <properties>
            <profile.active>dev</profile.active>
        </properties>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
    </profile>
    <profile>
        <id>pro_env</id>
        <properties>
            <profile.active>pro</profile.active>
        </properties>
    </profile>
    <profile>
        <id>test_env</id>
        <properties>
            <profile.active>test</profile.active>
        </properties>
    </profile>
</profiles>

②:SpringBoot中引用Maven属性
image.png

③:执行Maven打包指令

  • Maven指令执行完毕后,生成了对应的包,其中类参与编译,但是配置文件并没有编译,而是复制到包中

image.png

  • 解决思路:对于源码中非java类的操作要求加载Maven对应的属性,解析${}占位符

④:对资源文件开启对默认占位符的解析(另一个plugin,不是打jar包的那个)

<build>
    <plugins>
        <plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <configuration>
                <encoding>utf-8</encoding>
                <useDefaultDelimiters>true</useDefaultDelimiters>
            </configuration>
        </plugin>
    </plugins>
</build>
  • Maven打包加载到属性,打包顺利通过

image.png

5.启动命令

5.1SpringBoot项目快速启动

① 对SpringBoot项目打包(执行Maven构建指令package,执行前先clean)
② 执行启动指令
java -jar springboot_01_quickstart.jar # 项目的名称根据实际情况修改

注意事项:
**jar支持命令行启动需要依赖maven插件支持,请确认打包时是否具有SpringBoot对应的maven插件。**spring-boot-maven-plugin。会以fat jar 的形式打包,打完的jar中包含当前项目运行依赖的所有内容。

5.2带参数启动SpringBoot
java –jar springboot.jar --spring.profiles.active=test
java –jar springboot.jar --server.port=88
java –jar springboot.jar --server.port=88 --spring.profiles.active=test

image.png

5.3指令写入配置文件

如果指令太多,可以将指令写在File的配置文件中,也就是文件放置在jar包旁边再运行jar包

  • SpringBoot中4级配置文件
    • 1级: file :config/application.yml 【最高】
    • 2级: file :application.yml
    • 3级:classpath:config/application.yml
    • 4级:classpath:application.yml 【最低】
  • 作用:
    • 1级与2级留做系统打包后设置通用属性
    • 3级与4级用于系统开发阶段设置通用属性

6.SpringBoot整合JUnit

【第一步】添加整合junit起步依赖(可以直接勾选)

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

【第二步】编写测试类,默认自动生成了一个,添加@SpringBootTest注解即可代替之前的@Runwith等

@SpringBootTest
class Springboot07JunitApplicationTests {
    @Autowired
    private BookService bookService;

    @Test
    public void testSave() {
        bookService.save();
    }
}

使用junit5以上,如果是4则测试类需要Runwith注解(见专门的Junit总结)
只有测试类在启动类所在包或者子包里的时候,注解的参数(classes=启动类.class)才可以省略。此处类似于controller和启动类不在一起时,启动类需要扫包。

7.SpringBoot实现SSM整合

1 Spring整合MyBatis(复习)
  • SpringConfig
    • 导入JdbcConfig
    • 导入MyBatisConfig
@Configuration
@ComponentScan("com.itheima")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class, MyBatisConfig.class})
public class SpringConfig {

}
  • JDBCConfig
    • 定义数据源(加载properties配置项:driver、url、username、password)
#jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db
jdbc.username=root
jdbc.password=itheima
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 SqlSessionFactoryBean getSqlSessionFactoryBean(DataSource dataSource) {
    SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
    ssfb.setTypeAliasesPackage("com.itheima.domain");
    ssfb.setDataSource(dataSource);
    return ssfb;
}
@Bean
public MapperScannerConfigurer getMapperScannerConfigurer() {
    MapperScannerConfigurer msc = new MapperScannerConfigurer();
    msc.setBasePackage("com.itheima.dao");
    return msc;
}
2 SpringBoot整合MyBatis
  • SpringBoot整合Spring(不存在)
  • SpringBoot整合SpringMVC(不存在)
  • SpringBoot整合MyBatis(主要)
<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>2.2.0</version>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <scope>runtime</scope>
</dependency>
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.1.16</version>
</dependency>

①:创建新模块,选择Spring初始化,并配置模块相关基础信息
image.png

②:选择当前模块需要使用的技术集(web、MyBatis、MySQL)
image.png

③:设置数据源参数application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource

注意事项:SpringBoot版本低于2.4.3(不含),Mysql驱动版本大于8.0时,需要在url连接串中配置时区,或在MySQL数据库端配置时区解决此问题

jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC

最后一句用于设置druid连接池,使用前需要导包。

④:定义数据层接口与映射配置@Mapper

@Mapper
public interface UserDao {
    @Select("select * from tbl_book where id=#{id}")
    Book getById(Integer id);
}

注意:如果不使用@Mapper的话,则需要扫包,在启动类中,使用@MapperScanner进行扫包。
注意:类别名扫包处不需要再管,因为mybatis查询之后封装数据的结果对象,是作为返回值出现的,现在所有的返回值都加载。

⑤:测试类中注入dao接口,测试功能

@SpringBootTest
class Springboot08MybatisApplicationTests {
    @Autowired
    private BookDao bookDao;

    @Test
    public void testGetById() {
        Book book = bookDao.getById(1);
        System.out.println(book);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值