Spring Boot基础

Spring Boot简介

Spring 应用需要进行大量的配置,各种 XML 配置和注解配置让人眼花缭乱,为了简化 Spring 应用的搭建和开发过程,Pivotal 团队在 Spring 基础上提供了一套全新的开源的框架,它就是 Spring Boot。

SpringBoot 是构建在 SpringMVC 基础上的新一代 Web 开发框架,相比 SpringMVC,SpringBoot 的配置更简单。

在这里插入图片描述

pom 中加入对于 SpringBoot 的依赖:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
</parent>

<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>

Spring Boot 提供了大量开箱即用(out-of-the-box)的依赖模块,例如 spring-boot-starter-redis、spring-boot-starter-data-mongodb 和 spring-boot-starter-data-elasticsearch等。这些依赖模块为 Spring Boot 应用提供了大量的自动配置,使得 Spring Boot 应用只需要非常少量的配置甚至零配置,便可以运行起来,更多的精力专注于业务逻辑的开发。spring boot starter
在这里插入图片描述

Spring Boot应用

创建一个新的 SpringBoot 应用:

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


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

    private static Class<Application> applicationClass = Application.class;
}

MVC部分和Spring MVC一致:

@Controller
@RequestMapping("/test")
public class TestCtrl {
    @GetMapping("/hello")
    @ResponseBody
    public String Hello(){
        return "<h5>Hello Spring Boot</h5>";
    }

}

Spring Boot内置servlet容器和Tomcat服务器,并对Servlet又默认配置,直接启动主任务程序即可:

在这里插入图片描述
在这里插入图片描述
spring boot默认的上下文是/不是项目名,直接输入接口映射访问。

SpringBoot 内置了一个 Tomcat 服务器,也就是内嵌了一个 Servlet Container,因此直接运行工程就可以看到效果,不需要再进行额外的部署,也无需进行 Servlet 的有关配置。同时 SpringBoot 还会帮我们做许多配置工作。通过 @SpringBootApplication 这个 Annotation,它会帮我们打开 @EnableWebMvc,以及 @ComponentScan 功能,这意味着 SpringBoot 会和 SpringMvc 找到同一个 package 下的 @Controller,@Configuration 等类,进行自动配置。

Spring Boot配置文件

Spring boot免去各种依赖导入,和各种 XML 配置文件进行配归功于 Spring Boot 的 starter 机制。

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
数据库驱动所需参数,或服务参数都将在这些配置文件配配置。

YAML/YML/PROPERTIES

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
application.properties/yml/yaml是默认配置spring boot参数的,会被自动识别。

name: abc

# 对象
person:
  name: zhangsan
  age: 20

# 对象的行内写法
person1: {name: laowang,age: 20}

#数组
address:
  - beijing
  - shanghai

#数组行内写法
address1: [wuhan,hangzhou]

#变量
message1: 'hello \n world'  #原样输出
message2: "hello \n world"  #识别含义字符

#引用参数
description: ${message1}

获取配置参数

读取配置内容:
@Value注解
该注解读取配置文件定义的属性值,也可读取IoC容器的bean的属性,方法支持SpEl表达式。
Environment对象(配置文件对象)

//由于spring boot默认读取application.properties文件所以不用注解导入
@RestController
@RequestMapping("/print")
public class Test1Ctrl {

    @Value("${name}") private  String name;   //字符串注入
    @Value("${address[0]}") private String address;  //数组注入
    @Value("${person.name}") private String person;  //注入对象属性

    @Autowired
    private Environment environment;  //springboot默认读取的文件装配到配置文件对象

    @GetMapping("/name")
    public String printName(){
        return name;
    }

    @GetMapping("/list")
    protected String printList(){
        return address;
    }

    @GetMapping("/person")
    public String printPerson(){
        return person;
    }

    @GetMapping("/environment")
    public String printEnvironment(){
        return environment.getProperty("description");
    }

}

@ConfigurationProperties
将配置文件映射为一个配置类,在自动装配来获取值。

//Student.java:
@Component   //将该类注入到IoC容器
@ConfigurationProperties(prefix = "student")  //该注解实现了将配置文件映射为一个类,prefix绑定配置类的其中一个对象
public class Student {
    private String name;
    private String id;
}


//application.yaml
student:
  name: lihua
  id: s001


//controller
@RestController
@RequestMapping("/property")
public class Test2Ctrl {

    @Resource
    private Student student;   //注意将Student类注入IoC容器并通过@ConfigurationProperties注解将配置文件映射为一个bean

    @GetMapping("/student")
    protected Student printStudent(){
        return student;
    }
}

profile

开发Spring boot时,一套程序会被安装到不同的环境,如开发环境,测试环境,生产环境,其中数据库地址,服务器端口等配置都不同,如果每次打包都要修改配置文件很麻烦,profile功能就是用来进行动态配置切换的。

  • profile的配置方式
  1. 多profile文件方式
    在这里插入图片描述
    在这里插入图片描述
    在主配置文件中设置激活的配置文件,该文件就会生效。

  2. yml多文档方式

通过---分割不同工作区。

  • profile的激活方式
  1. 配置文件

上面配置文件中active属性等于谁就启动谁

  1. 虚拟机命令
    在这里插入图片描述

  2. 命令行参数

Spring boot可以打成jar包通过java -jar [jar包路径]即可运行项目,在该命令后配置启动参数文件java -jar [jar包路径] --spring.profiles.active=pro即可启动active=pro的配置。

配置文件加载顺序

在这里插入图片描述
每个配置文件都会加载,重复的优先级高的生效。除了内部配置文件的配置,也可以通过命令行实现外部文件的配置,在运行jar包时,配置响应的参数,或直接新的配置文件的位置来覆盖内部配置。

静态资源默认读取目录

在这里插入图片描述

Spring boot整合其他框架

  • 单元测试

引入starter-test依赖;在测试类上添加注解、@RunWith(SpringRunner.class)和@SpringBootTest(class=启动类.class)

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootDemoApplication.class)
public class UserTest {
    @Autowired
    private UserService userService;

    @Test
    public void addTest(){
        userService.userAdd();
    }
}

//别忘了将测试类注入IoC容器
@Service
public class UserService {
    public void userAdd(){
        System.out.println("add...");
    }

}

在这里插入图片描述

  • 整合Redis
    导入Redis依赖,配置redis,注入RedisTemplates模板

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <scope>test</scope>
        </dependency>
spring:
  redis:
    host: 127.0.0.1
    port: 6379
 @Autowired
    private RedisTemplate redisTemplate;

    public void redisTest(){
        redisTemplate.boundValuesOps("name").set("zhangsan");

        Object name=redisTemplate.boundValuesOps("name").get();
        System.out.println(name);
    }
  • 整合mybatis

引入mybatis依赖,和数据库驱动;编写DataSource和myabtis的相关配置,定义需要的实体类实现dao和mapper注解,或配置文件开发开发。

<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

Mybatis可以注解开发也可以配置文件开发,方法如下:

注解开发

  1. yml的datasource配置

spring boot的默认application配置文件提供了datasource的配置,按照规定的语法写,就能被spring识别,当然能也可以导入druid连接池再配置datasource数据源。


#datasource配置

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/[数据名]?characterEncoding=utf-8
    password: ...
    username: ...


  1. @Mapper注解代替xml配置文件

从mybatis3.4.0开始加入了@Mapper注解,代替xml配置文件,实现完全注解开发,在普通项目中我们需要读取xml配置文件,构建SqlSessionFactory和SqlSession获取Mapper类,再调用方法。而@Mapper注解集成了这些功能,无需配置。注解在一个Mapper映射类上,就能完成SqlSessionFactory和SqlSession的创建,并调用getMapper()方法返回一个Mapper类。

在这里插入图片描述
spring也提供了@MapperScan是org.mybatis.spring的注解共差不多。
在这里插入图片描述

  1. 编写POJO
public class User {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
  1. 编写测试类
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootDemoApplication.class)
public class UserTest {
    //数据库测试变量
    @Autowired
    private UserMapper userMapper;
    @Test
    public void selectAll(){
        List<User> list= userMapper.selectAll();
        System.out.println(list);
    }
}

//spring自动创建SqlSession调用getMapper()方法

在这里插入图片描述

  • spring boot 的mybatis的xml配置开发

ssm项目中xml配置文件路径和mapper映射路径都是需要配置的并注入IoC容器的,spring boot由默认的配置,有的需要覆盖成自己的在指定位置覆盖生效applicationssm环境搭建

  1. application文件中对mybatis的默认配置进行覆盖。(mybatis-spring-boot-starter导入时就有默认配置了)
# datasource
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db1?characterEncoding=utf-8
    password: ...
    username: ...

# mybatis配置
mybatis:
  config-location:   #指定mybatis核心配置文件,用默认配置即可
  mapper-locations: classpath:mapper/*Mapper.xml   #mapper.xml映射路径
  type-aliases-package: com.example.springbootdemo.model     #配置resultType等类型的全限定名,然后resultType=类名即可

映射路径需要覆盖默认配置。

  1. 编写mapper.xml配置文件和映射mapper类
<?xml version="1.0" encoding="UTF-8" ?>
        <!DOCTYPE mapper
                PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
                "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.springbootdemo.dao.UserMapper">
<select id="selectAll" resultType="com.example.springbootdemo.model.User">
<!-- type-aliases-package进行了配置这里可以直接写User-->
    select * from user
</select>
</mapper>

如果没配置type-aliases-package又没写全就会出现这样的错误:
在这里插入图片描述

@Repository
@Mapper
public interface UserMapper {
    //@Select("select * from user")
    List<User> selectAll();
}
  1. POJO和上面的User一样,测试类如下
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootDemoApplication.class)
public class UserTest {
 
    //数据库测试变量
    @Autowired
    private UserMapper userMapper;

    @Test
    public void selectAll(){
        List<User> list= userMapper.selectAll();
        System.out.println(list);
    }

在这里插入图片描述
由此可以看出,注解开发比配置文件开发更简单,少了一个@Select,@Insert…的注解,却多了mybatis的覆盖配置参数,mapper.xml文件,mapper接口,其他都一样。除了很难的sql语句建议注解开发。

Spring Boot自动配置

Spring Boot的最大的特点就是简化了各种xml配置内容,省去了SSM框架各种xml配置,如:数据源、连接池、会话工厂、事务管理等。spring实现完全注解开发,Spring Boot就是全用注解来对一些常规的配置做默认配置,简化xml配置内容,使你的项目能够快速运行。

感谢作者@牧竹子
感谢作者@
感谢作者@Java3y
感谢以上作者虽然我还看不懂 😐。

@Enable*注解
Spring Boot注解提供了提供了很多该注解盖头的注解,用于开启某些功能,底层时使用@Import注解到日一些配置类,实现bean的动态加载。

@Enable注解依赖@Import注解导入的类会被spring加载到IoC容器,@Enable注解导入@Import注解。

@EnableAutoConfiguration注解

该注解内部使用@Inport(AutoConfiggurationImportSelector.class)来加载类。
配置问津位置:META-INF/spring.factories,该注解定义了大量配置类,当spring启动时,会加载这些配置类,初始化bean。

Spring Boot切换内置web服务器

spring boot的web环境默认使用Tomcat服务器,但Spring boot内置了四种服务器可供选择:jetty,
netty,tomcat,undertow

<!--将tomcat排除-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   		<artifactId>spring-boot-starter-web</artifactId>
		<executions>
			<exclusions>
				<artifactId>spring-boot-starter-tomcat</artifactId>
				<groupId>org.springframework.boot</groupId>
			</exclusions>
		</executions>
<dependency>
<!--引入新的服务器依赖-->
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
            <scope>test</scope>
        </dependency>

Spring Boot事件监听

spring监听机制是对java提供的监听机制的封装。java事件的监听机制又以下几个类:

  • Event:继承java.util.EventObject类的对象
  • 事件源Source:任意Object对象
  • 监听器Listenter:实现java.util.EventListenter接口的对象

spring boot的监听器:

  • ApplicationContextInitializer
  • SpringApplicationRunListener
    在这里插入图片描述

从上到下依次是:项目启动中,环境开始准备,环境准备完毕,上下文开始加载,上下文加载完成,项目启动完成,项目启动失败的项目声明周期函数

上面要生效需要配置,再spring boot项目中的resources目录下创建MATA-INF/spring.factores并配置:

org.springframework.contex.ApplicationContextInitializer=exanple.text.listenerMyApplicationContextInitializer


//前面是监听器,后面是自定义的实现类
//注意都要写全限定名

//SpringApplicationRunListener的配置一样,再实现类重写方法实现监听

//SpringApplicationRunListener需要重写有参构造方法,参数为事件源和agrs的String数组
  • CommandLineRunner
    接口偶一个run方法,当项目启动后执行run方法。
  • ApplicationRunner
    接口偶一个run方法,当项目启动后执行run方法。

Spring Boot监控

spring boot自带监控功能,可以实现对程序的内部运行情况监控,比如bean加载情况,配置属性,日志信息等。

  1. 导入依赖坐标
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <scope>test</scope>
        </dependency>
  1. 启动程序,访问http://localhost:8080/actuator

模板引擎

在java领域,表现层技术主要有四种:jspfreemarkervelocityThymeleaf

对于传统jsp或者其他模板来说,没有一个模板引擎的后缀为.html,就拿jsp来说jsp的后缀为.jsp,它的本质就是在一个html文件java语法、标签然后执行时候通过后台的jre重新编译这个文件最终返回一个html页面,离不开服务端,浏览器端是无法直接识别.jsp文件。

执行过程中依赖于服务端的jre
在这里插入图片描述
JSP模板引擎

freemarker

Spring Boot项目部署

spring boot项目支持两种方式部署到服务器

  1. jar包

用IDE打成jar包,再上传到服务器,再同一目录下java -jar [jar包]

  1. war包

在pom中修改打包方式<packaging>war</packaging>,主程序继承SpringBootServletInitializer并重写一个方法:

@SpringBootApplication
public class SpringbootupdateApplication extends SpringBootServletInitializer {

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

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(SpringbootupdateApplication.class);
    }
}

可以在<build>标签中用指定打包名称:


    <build>
        <finalName>${filename}</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

打包后直接将war文件放在tomcat中就可以了,上下文连接变成了war包的名称。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xvwen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值