SpringBoot之快速入门——笔记

213 阅读6分钟

前言

1、在学习了SSM框架以后,对于Spring全家桶框架内开发有了一定的理解,但是一直对于繁琐的xml配表深感不耐。不过有时候想想之前学得Servlet原生开发,以及没有用Mybatis的映射开发处理服务器数据,那JDBC重复代码,那数据库连接池注册,种种酸爽,更加上头。

2、为了纪念这个曾经让我写吐的重复代码,特此贴条:

Spring工程热部署:

开发过程中,反复修改类在所难免,这时候反复启动SpringBoot就很消耗时间和耐性,可以用到SpringBoot工程热部署。

1、首先,在pom.xml中配置相关坐标

<!--热部署配置-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>

2、然后再Idea中设置相关热部署操作。

3、然后要按一个非常蛇皮的快捷键组合,这里推荐在设置里找到**Maintenance**,然后改快捷键。

起步依赖:

1、在一个Spring框架工程创建中,可以选择多种技术集合,Redis啊,Spring Web啊,在这里我以Spring Web举例,分析它的内部依赖关系。

2、首先可以明确一点,SpringBoot给我们Pom.xml的是最小辈,而它的父亲,负责的工作是整合导入Jar包:

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-dependencies</artifactId>
  <version>2.0.1.RELEASE</version>
  <relativePath>../../spring-boot-dependencies</relativePath>
</parent>
<artifactId>springboot_quick2</artifactId>

3、而在父亲的配置里面,可以很清晰的看到有一个爷爷辈。

<parent>
    	<groupId>org.springframework.boot</groupId>
    	<artifactId>spring-boot-starters</artifactId>
    	<version>2.0.1.RELEASE</version>
  	</parent>
  	<groupId>org.springframework.boot</groupId>
</parent>

4、爷爷辈主要负责的是进行版本控制:(截取一部分)

5、通过这些功能我们可以得知,其实Spring传递依赖也是通过Maven的传递依赖来实现的。
  • 自动配置原理解析

1、按住Ctrl点击查看启动类MySpringBootApplication上的注解@SpringBootApplication。

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

2、注解@SpringBootApplication的源码

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
		@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

	/**
	 * Exclude specific auto-configuration classes such that they will never be applied.
	 * @return the classes to exclude
	 */
	@AliasFor(annotation = EnableAutoConfiguration.class)
	Class<?>[] exclude() default {};

	... ... ...

}

3、其中,

@SpringBootConfiguration:等同与@Configuration,既标注该类是Spring的一个配置类

@EnableAutoConfiguration:SpringBoot自动配置功能开启,这也是重点之一。

按住Ctrl点击查看注解@EnableAutoConfiguration

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
	... ... ...
}

4、其中,@Import(AutoConfigurationImportSelector.class) 导入了AutoConfigurationImportSelector

按住Ctrl点击查看AutoConfigurationImportSelector源码

public String[] selectImports(AnnotationMetadata annotationMetadata) {
        ... ... ...
        List<String> configurations = getCandidateConfigurations(annotationMetadata,
                                                                   attributes);
        configurations = removeDuplicates(configurations);
        Set<String> exclusions = getExclusions(annotationMetadata, attributes);
        checkExcludedClasses(configurations, exclusions);
        configurations.removeAll(exclusions);
        configurations = filter(configurations, autoConfigurationMetadata);
        fireAutoConfigurationImportEvents(configurations, exclusions);
        return StringUtils.toStringArray(configurations);
}

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
			AnnotationAttributes attributes) {
		List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
				getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());

		return configurations;
}

5、其中,SpringFactoriesLoader.loadFactoryNames 方法(下面那个)的作用就是从META-INF/spring.factories文件中读取指定类对应的类名称列表 

6、打开spring.factories 文件:

... ... ...

org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\

... ... ...

7、我们用**ServletWebServerFactoryAutoConfiguration举例,进入她的类当中。可以看到她有个大概叫做能够配置属性的注解,具体作用就是可以加载这个类里面的数据(从spring-configuration-metadata.json,也就是前两张图中META-INF下的json文件**)

8、这个类中,就是负责申明各种需要自动配置的属性,命名规则为“server.”前缀加下面的字段名。

9、spring-configuration-metadata.json,也就是前两张图中META-INF下的json文件下找到的server.port,最后注入给ServletWebServerFactoryAutoConfiguration中。

10、这些是在没声明前的默认加载配置,如果我们要修改配置呢,就比如说我要改我的这个Spring自带集成的tomcat里的服务器端口号,怎么修改呢?

其实很简单,因为SpringBoot是基于约定的,所以很多配置都有默认值,但如果想使用自己的配置替换默认配置的话,就可以使用application.properties或者application.yml(application.yaml)进行配置。

在Reources文件夹下c一个application.properties,写自己要修改的属性:

11、这时候问题又来了,要是我不知道我需要读写的数据key值咋办呢(比如说不知道服务器端口号的key.name)?下面列举顺便记忆一些常用keyname。

# QUARTZ SCHEDULER (QuartzProperties)
spring.quartz.jdbc.initialize-schema=embedded # Database schema initialization mode.
spring.quartz.jdbc.schema=classpath:org/quartz/impl/jdbcjobstore/tables_@@platform@@.sql # Path to the SQL file to use to initialize the database schema.
spring.quartz.job-store-type=memory # Quartz job store type.
spring.quartz.properties.*= # Additional Quartz Scheduler properties.

# ----------------------------------------
# WEB PROPERTIES
# ----------------------------------------

# EMBEDDED SERVER CONFIGURATION (ServerProperties)
server.port=8080 # Server HTTP port.
server.servlet.context-path= # Context path of the application.
server.servlet.path=/ # Path of the main dispatcher servlet.

# HTTP encoding (HttpEncodingProperties)
spring.http.encoding.charset=UTF-8 # Charset of HTTP requests and responses. Added to the "Content-Type" header if not set explicitly.

# JACKSON (JacksonProperties)
spring.jackson.date-format= # Date format string or a fully-qualified date format class name. For instance, `yyyy-MM-dd HH:mm:ss`.

# SPRING MVC (WebMvcProperties)
spring.mvc.servlet.load-on-startup=-1 # Load on startup priority of the dispatcher servlet.
spring.mvc.static-path-pattern=/** # Path pattern used for static resources.
spring.mvc.view.prefix= # Spring MVC view prefix.
spring.mvc.view.suffix= # Spring MVC view suffix.

# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.driver-class-name= # Fully qualified name of the JDBC driver. Auto-detected based on the URL by default.
spring.datasource.password= # Login password of the database.
spring.datasource.url= # JDBC URL of the database.
spring.datasource.username= # Login username of the database.

# JEST (Elasticsearch HTTP client) (JestProperties)
spring.elasticsearch.jest.password= # Login password.
spring.elasticsearch.jest.proxy.host= # Proxy host the HTTP client should use.
spring.elasticsearch.jest.proxy.port= # Proxy port the HTTP client should use.
spring.elasticsearch.jest.read-timeout=3s # Read timeout.
spring.elasticsearch.jest.username= # Login username.

要是还觉得不够怎么办呢?来人,喂公子吃饼(常用文档参考)!

docs.spring.io/spring-boot…

12、接下来马上就要用到其中的数据库连接键值对。

yml文件的简单了解

1、普通数据

name: haohao

2、对象数据

person:
  name: haohao
  age: 31
  addr: beijing

#或者

person: {name: haohao,age: 31,addr: beijing}

3、Map数据

同上

4、配置数组(List、Set)数据

city:
  - beijing
  - tianjin
  - shanghai
  - chongqing

#或者

city: [beijing,tianjin,shanghai,chongqing]

#集合中的元素是对象形式
student:
  - name: zhangsan
    age: 18
    score: 100
  - name: lisi
    age: 28
    score: 88
  - name: wangwu
    age: 38
    score: 90

通过@Value和@ConfigurationProperties来操作yml文件里的信息

这里提一句,SpringBoot会先读取yml文件,再读取properties,如果两个文件里有相同的属性,后者会覆盖前者,还是**properties大哥优先级高**。

接下来就是在实体Bean中读取yml表的数据:

通过@Value和el表达式来获取yml表对应的数据。

@Controller
public class QuickStartController {

    @Value("${person.name}")
    private String name;
    @Value("${person.age}")
    private Integer age;

    @RequestMapping("/quick")
    @ResponseBody
    public String quick(){
        return "springboot 访问成功! name="+name+",age="+age;
    }

}

通过@ConfigurationProperties,在Bean类中给予字段SetGet方法,就能在properties或者yml文件里进行配置文件与实体字段的自动映射。美滋滋。

SpringBoot的集成其他技术

1、整合Mybatis

  • 引入mybatis的坐标,和数据库连接坐标,为什么还需要引入一个数据库坐标呢?因为SpringBoot不知道你是要连接哪个数据库。

    org.mybatis.spring.boot mybatis-spring-boot-starter 1.1.1 mysql mysql-connector-java
  • 接下来就是喜闻乐见的配置数据库连接信息,在application.properties中。

    #DB Configuration: spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=root

  • 以及原本应该放在核心配置类里的简写包扫描和映射文件配置表扫描

    #spring集成Mybatis环境 #pojo别名扫描包 mybatis.type-aliases-package=com.itheima.domain #加载Mybatis映射文件 mybatis.mapper-locations=classpath:mapper/*Mapper.xml

  • 接下来就是Bean实体类,映射类,以及映射类xml配置的操作,有点过于赘述,不写了。直接贴测试类。

    @Controller public class MapperController {

    @Autowired
    private UserMapper userMapper;
    
    @RequestMapping("/queryUser")
    @ResponseBody
    public List<User> queryUser(){
        List<User> users = userMapper.queryUserList();
        return users;
    }
    

    }

2、整合Redis

添加redis的起步依赖

<!-- 配置使用redis启动器 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

配置redis的连接信息

#Redis
spring.redis.host=127.0.0.1
spring.redis.port=6379

注入RedisTemplate测试redis操作

入门到这一步先结束,接下来要在实战中总结经验,提升自己。