SpringBoot 基础

一、SpringBoot基础篇

1.SpringBoot初探

​ SpringBoot的初衷简化配置

2.SpringBoot项目的构建方式

2.1 通过官网自动生成

https://start.spring.io/ 快速生成
在这里插入图片描述

2.2 IDE 在线模板生成

本质上和上面是一样的,只是简化了我们的操作

2.3 IDE通过maven项目构建

1.创建一个独立的web项目

2.引入对应依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.15.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

3.添加对应的启动器

@SpringBootApplication
public class GpSpringBootApplication {

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

4.启动启动器的主方法

测试即可

3.SpringBoot中的常规配置

3.1 入口类和相关注解

@SpringBootApplication
public class GpSpringbootDemo02Application {

    public static void main(String[] args) {
        // Spring IoC 容器的初始化
        ApplicationContext ac = SpringApplication.run(GpSpringbootDemo02Application.class, args);
    }
}

main方法:

​ 其实完成的就是一个SpringIoC容器的初始化操作

@SpringBootApplication注解

​ 1.在IoC初始化的时候会加载该注解

​ 2.是一个组合注解

@Target({ElementType.TYPE}) // 注解可以写在哪些地方
@Retention(RetentionPolicy.RUNTIME) // 该注解的作用域  RESOURCES CLASS RUNTIME
@Documented // 该注解会被API抽取
@Inherited  // 可继承
// 以上四个是Java中提供的元注解
@SpringBootConfiguration // 本质上就是一个Configuration注解
@EnableAutoConfiguration // 自动装配的注解
@ComponentScan( // 扫描 会自动扫描 @SpringBootApplication所在的类的同级包(com.gupaoedu)以及子包中的Bean,所有一般我们建议将入口类放置在 groupId+artifcatID的组合包下
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)

3.2 Banner

http://patorjk.com/software/taag (在线生成文字图标地址)
在这里插入图片描述

在resources目录下创建一个 banner.txt文件

关闭Banner

public static void main(String[] args) {
    // Spring IoC 容器的初始化
    SpringApplication springApplication = new SpringApplication(GpDblSpringbootServletApplication.class);
    springApplication.setBannerMode(Banner.Mode.OFF);// 关闭Banner
    springApplication.run(args);
}

3.3 常规配置

​ 在SpringBoot中给我们提供的有两个配置文件 applicationContext.properties,applicationContext.yml 作用是一样的,一个项目中只需要其中的一个就可以了。

Tomcat配置修改

server.port=8082
server.servlet.context-path=/springboot

自定义的属性

# 自定义的配置信息
user.username=dbl
user.age=18
user.address=成都

获取

@Value("${user.username}")
private String userName;

@Value("${user.age}")
private Integer age;
@Value("${user.address}")
private String address;

中文乱码问题

server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8

类型安全配置

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
package com.gp.dbl.bean;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * descrription:
 * <p>
 * Create by DbL on 2020/10/25
 */
@Component
// 属性文件中的属性和User对象中的成员变量映射
@ConfigurationProperties(prefix = "user")
public class User {

    private String username;

    private Integer age;

    private String address;


    public String getUsername() {
        return username;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                '}';
    }
}

3.4 Logback日志

SpringBoot内置的有Logback的依赖

直接在属性文件中简单配置

# logback的配置
logging.file=d:/log.log
logging.level.org.springframework.web=DEBUG

单独提供一个logback.xml

3.5 Profile

命名规则application-xxx.properties

spring.profiles.active=xxx # 指定对应的环境

4.SpringBoot中的静态资源

4.1 static目录

SpringBoot默认的存放静态资源的目录
在这里插入图片描述

4.2 webapp目录

在resources同级目录下创建一个webapp目录,该目录的类型必须是ResourcesRoot

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EiXu29tA-1603635562604)(img\1595313425458.png)]

4.3 自定义静态资源路径

自定义目录后,创建对应的相关资源,然后在属性文件中去覆盖静态资源的路径配置即可

# 表示所有的访问都经过静态资源路径
spring.webflux.static-path-pattern=/**

# 覆盖默认的配置,所有需要将默认的static public等这些路径将不能作为静态资源的访问
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/custom

5.自动装配的原理

5.1 starter

名称描述
spring-boot-starter-thymeleaf使MVC Web applications 支持Thymeleaf
spring-boot-starter-data-couchbase使用Couchbase 文件存储数据库、Spring Data Couchbase
spring-boot-starter-artemis为JMS messaging使用Apache Artemis
spring-boot-starter-web-services使用Spring Web Services
spring-boot-starter-mailJava Mail、Spring email为邮件发送工具
spring-boot-starter-data-redis通过Spring Data Redis 、Jedis client使用Redis键值存储数据库
spring-boot-starter-web构建Web,包含RESTful风格框架SpringMVC和默认的嵌入式容器Tomcat
spring-boot-starter-activemq为JMS使用Apache ActiveMQ
spring-boot-starter-data-elasticsearch使用Elasticsearch、analytics engine、Spring Data Elasticsearch
spring-boot-starter-integration使用Spring Integration
spring-boot-starter-test测试 Spring Boot applications包含JUnit、 Hamcrest、Mockito
spring-boot-starter-jdbc通过 Tomcat JDBC 连接池使用JDBC
spring-boot-starter-mobile通过Spring Mobile构建Web应用
spring-boot-starter-validation通过Hibernate Validator使用 Java Bean Validation
spring-boot-starter-hateoas使用Spring MVC、Spring HATEOAS构建 hypermedia-based RESTful Web 应用
spring-boot-starter-jersey通过 JAX-RS、Jersey构建 RESTful web applications;spring-boot-starter-web的另一替代方案
spring-boot-starter-data-neo4j使用Neo4j图形数据库、Spring Data Neo4j
spring-boot-starter-websocket使用Spring WebSocket构建 WebSocket 应用
spring-boot-starter-aop通过Spring AOP、AspectJ面向切面编程
spring-boot-starter-amqp使用Spring AMQP、Rabbit MQ
spring-boot-starter-data-cassandra使用Cassandra分布式数据库、Spring Data Cassandra
spring-boot-starter-social-facebook使用 Spring Social Facebook
spring-boot-starter-jta-atomikos为 JTA 使用 Atomikos
spring-boot-starter-security使用 Spring Security
spring-boot-starter-mustache使MVC Web applications 支持Mustache
spring-boot-starter-data-jpa通过 Hibernate 使用 Spring Data JPA (Spring-data-jpa依赖于Hibernate)
spring-boot-starterCore starter,包括 自动配置支持、 logging and YAML
spring-boot-starter-groovy-templates使MVC Web applications 支持Groovy Templates
spring-boot-starter-freemarker使MVC Web applications 支持 FreeMarker
spring-boot-starter-batch使用Spring Batch
spring-boot-starter-social-linkedin使用Spring Social LinkedIn
spring-boot-starter-cache使用 Spring caching 支持
spring-boot-starter-data-solr通过 Spring Data Solr 使用 Apache Solr
spring-boot-starter-data-mongodb使用 MongoDB 文件存储数据库、Spring Data MongoDB
spring-boot-starter-jooq使用JOOQ链接SQL数据库;spring-boot-starter-data-jpa、spring-boot-starter-jdbc的另一替代方案
spring-boot-starter-jta-narayanaSpring Boot Narayana JTA Starter
spring-boot-starter-cloud-connectors用连接简化的 Spring Cloud 连接器进行云服务就像Cloud Foundry、Heroku那样
spring-boot-starter-jta-bitronix为JTA transactions 使用 Bitronix
spring-boot-starter-social-twitter使用 Spring Social Twitter
spring-boot-starter-data-rest使用Spring Data REST 以 REST 方式暴露 Spring Data repositories
spring-boot-starter-actuator使用Spring Boot Actuator 的 production-ready 功能来帮助你监视和管理应用
spring-boot-starter-undertow使用 Undertow 作为嵌入式服务容器;spring-boot-starter-tomcat的另一替代方案
spring-boot-starter-jetty使用 Jetty 作为嵌入式服务容器;spring-boot-starter-tomcat的另一替代方案
spring-boot-starter-logging为 logging 使用Logback.默认 logging starter
spring-boot-starter-tomcat使用 Tomcat 作为嵌入式服务容器;作为默认嵌入式服务容器被spring-boot-starter-web使用
spring-boot-starter-log4j2使用Log4j2记录日志;spring-boot-starter-logging的另一替代方案

5.2 自动装配

@EnableAutoConfiguration
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

    Class<?>[] exclude() default {};

    String[] excludeName() default {};
}

通过@EnableAutoConfiguration注解发现。其本身就是一个组合注解,有一个注解我们必须要弄清楚@Import注解

@Import

在Spring中我们将类型交给SpringIoC管理的方式有哪些?

1.基于xml配置文件

2.基于xml配置文件@Component

3.基于Java配置类【@Configuration】 @Bean

4.基于Java配置类+@ComponentScan+@Component

5.FactoryBean接口【getObject()】

6.@Import注解

第一种使用方式

静态使用方式

@Configuration
@Import(UserService.class)
public class JavaConfig {

    /*@Bean
    public UserService getUserSerivce(){
        return new UserService();
    }*/
}

在@Import注解中直接指定要添加的类型

缺点:直接在@Import中写死要注入的类型,不太灵活

第二种使用方式

ImportSelector接口

/**
 * descrription:
 * <p>
 * Create by DbL on 2020/10/25
 */
public class GpDBLImportSelector implements ImportSelector {
    /**
     *  动态获取IoC要加载的类型
     * @param annotationMetadata 注解的元数据
     * @return
     *     IoC要加载的类型的数组
     */
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        // 根据不同的业务逻辑 实现动态添加IoC加载的类型
        /*if (){

        }*/
        return new String[]{LoggerService.class.getName(),CacheService.class.getName()};
    }
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(GpImportSelector.class)
public @interface EnableGpImport {
}

是将@Import注解中添加的 ImportSelector的实现类中的selectImports这个方法返回的字符串数组加载到IoC容器中

第三种实现方式

实现ImportBeanDefinitionRegistrar接口,其实和第二种方式很类似,都是在源码设计层面用的比较多。

/**
 * descrription:
 * <p>
 * Create by DbL on 2020/10/25
 */
public class GpDBLImportBeanDefinition implements ImportBeanDefinitionRegistrar {
    /**
     *  提供了一个beanDefinition的注册器,我直接把需要IoC加载的类型注册到容器中去
     * @param annotationMetadata
     * @param beanDefinitionRegistry beanDefinition的注册器
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        // 将我们需要添加的类型统一封装为RootBeanDefinition对象
        RootBeanDefinition cache = new RootBeanDefinition(CacheService.class);
        beanDefinitionRegistry.registerBeanDefinition("cache",cache);
        RootBeanDefinition logger = new RootBeanDefinition(LoggerService.class);
        beanDefinitionRegistry.registerBeanDefinition("logger",logger);
    }
}

原理分析
public String[] selectImports(AnnotationMetadata annotationMetadata) {
    if (!this.isEnabled(annotationMetadata)) {
        return NO_IMPORTS;
    } else {
        // 加载META-INF/spring-autoconfigure-metadata.properties
        AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
        AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata);
        // 返回需要IoC加载的类型数组
        return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
    }
}
protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata, AnnotationMetadata annotationMetadata) {
    if (!this.isEnabled(annotationMetadata)) {
        return EMPTY_ENTRY;
    } else {
        AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
        // 获取候选的配置信息 META-INF/spring.factories 加载了很多的 类路径
        List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
        // 去掉重复的
        configurations = this.removeDuplicates(configurations);
        // 去掉要排除掉的类型
        Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
        this.checkExcludedClasses(configurations, exclusions);
        configurations.removeAll(exclusions);
        // 过滤器
        configurations = this.filter(configurations, autoConfigurationMetadata);
        // 广播
        this.fireAutoConfigurationImportEvents(configurations, exclusions);
        return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
    }
}

自动装配的原理:

1.在SpringBoot项目启动的时候,会加载SpringBootApplication这个注解

2.会解析@EnableAutoConfiguration注解

3.与之对应的解析@Import注解

4.执行ImportSelector接口的的实现

5.加载META-INF/spring-autoconfigure-metadata.properties中的注解元数据信息

6.加载META-INF/spring.factories各种类路径【第三方扩展也同样的会加载对应的文件 SPI扩展机制】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值