SpringBoot——入门及原理

news2024/10/6 6:43:20

SpringBoot用来简化Spring应用开发,约定大于配置,去繁从简,是由Pivotal团队提供的全新框架。其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置(有特殊需求可以添加自己的配置覆盖默认配置),从而使开发人员不再需要定义样板化的配置。SpringBoot可以看成是J2EE的一站式解决方案。

一、SpringBoot 的优点

【1】快速创建独立运行的Spring项目以及与主流框架集成。
【2】使用嵌入式的Servlet容器,应用无需打成war包,可以打成jar包,通过java -jar的方式直接运行。
【3】starters(启动器)自动依赖与版本控制。
【4】大量的自动配置,简化开发,也可以修改默认值。
【5】无需配置XML,无代码生成,开箱即用。
【6】准生产环境的运行时应用监控。
【7】与云计算的天然集成。

二、解决微服务部署和运维难的问题:Spring Boot

 如上的流程依次为: 搭建项目 构建连接 批处理

三、Spring Boot 入门项目

HelloWorld(也可以参考五,快速创建一个 SpringBoot项目)

【1】准备环境:Mavensettings.xml配置文件的profiles标签添加如下信息:

<profile>
<id>jdk-1.8</id>
<activation>
    <activeByDefault>true</activeByDefault>
    <jdk>1.8</jdk>
</activation>
<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
</properties>
</profile>

【2】将IDEAMaven更换为我们自己本地安装的Maven。(自行百度更换)创建一个maven工程[jar],在pom.xml中导入如下依赖:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

【3】编写一个主程序,启动SpringBoot应用

@SpringBootApplication
public class Hello {
   public static void main(String[] args) throws Exception {
       //启动spring应用
       SpringApplication.run(Hello.class, args);
   }
}

【4】编写相关的ControllerService

@Controller
public class HelloController {
   @ResponseBody
   @RequestMapping("/hello")
   public String hello(){
       return "hello world!";
   }
}

【5】运行主测试程序。简化部署应用<可以将应用打包成一个可执行的jar包>:通过Maven Projects中 的package(双击)即可。生成jar的位置:默认在项目的target目录下的“项目名称.jar”文件。运行jar:在命令行可以通过 “java -jar jar文件名.jar” 命令运行项目。

<build>
   <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
   </plugins>
</build>

四、Hello World 探究(POM文件)

【1】父项目[spring-boot-starter-parent]:

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

【2】进入spring-boot-starter-parent发现它还有一个父项目 :

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

【3】进入spring-boot-dependencies后,发现如下信息,与之前我们创建的分布式项目继承的Maven父项目功能是一样的,用来管理所有jar包依赖的版本。称为SpringBoot的版本仲裁中心,以后我们导入依赖默认是不需要写版本;(没有在dependencies里面管理的依赖,需要声明版本号)

<properties>
    <activemq.version>5.15.3</activemq.version>
    <antlr2.version>2.7.7</antlr2.version>
    <appengine-sdk.version>1.9.62</appengine-sdk.version>
    <artemis.version>2.4.0</artemis.version>
    <aspectj.version>1.8.13</aspectj.version>
    <assertj.version>3.9.1</assertj.version>
    <... 此处省略 .../>
</properties>

【4】启动器[spring-boot-starter-web]

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

spring-boot-starter-webspring-boot-starterspring-boot场景启动器;进入官网可以到有许多场景启动器,简单点说就是通过此功能将相关jar包给组合在起来,我们使用时只需要引入一个Web Starter就可以轻松搞定。Spring Boot将所有的功能场景都抽取出来,做成一个个的 starters(启动器),只需要在项目里面引入这些starter相关场景,所有依赖都会导入进来。要用什么功能就导入什么场景启动器。

点击web右边的pom可以看到SpringBoot为我们依赖的其它jar包,帮我们导入了web模块正常运行所依赖的所有组件。如下:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
    </dependency>
</dependencies>

【5】主程序类(Java类):@SpringBootApplication:此注解声明的类,是SpringBoot的主配置类,SpringBoot就应该运行这个类的main方法来启动SpringBoot

//@ImportResource(locations={"classpath:bean.xml"})
//@SpringBootApplication 来标注一个主程序类,说明这是一个SpringBoot应用
@SpringBootApplication
public class HellowordQuickStartApplication {

    public static void main(String[] args) {
        /*SpringBoot应用启动项
        HellowordQuickStartApplication.class 参数必须是用@SpringBootApplication注解修饰的类
        */
        SpringApplication.run(HellowordQuickStartApplication.class, args);
    }
}

@SpringBootApplication(主要由:@SpringBootConfiguration/@EnableAutoConfiguration/@ComponentScan组成)

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

@SpringBootConfiguration:标注在某个类上,表示此类是一个SpringBoot的配置类。由以下注解组合形成:配置类 == 配置文件,配置类也是容器的一个组件,底层由@Component等等组成。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration //表示此类是一个配置类  是spring的一个组件
public @interface SpringBootConfiguration {

@EnableAutoConfiguration:开启自动配置功能。也是一个组合注解,由以下注解组成(部分重要注解):

@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

@AutoConfigurationPackage:自动依赖相关的配置包,也是一个组合注解,主要由@import等注解组合

@Import({Registrar.class})//给容器中导入一个组件;导入的组件由此组建决定。
public @interface AutoConfigurationPackage {

进入@Import(Registrar.class)中的Registrar类中,通过断点,可以查看到我注释的一些信息。

static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {
    Registrar() {
    }
    //registerBeanDefinitions方法中的metadata可以查看到我们启动类使用的注解 @SpringBootApplication
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        AutoConfigurationPackages.register(registry, new String[]{(new AutoConfigurationPackages.PackageImport(metadata)).getPackageName()});
    }
    //new AutoConfigurationPackages.PackageImport(metadata) 可以解析出我们当前主启动所在的package包
    public Set<Object> determineImports(AnnotationMetadata metadata) {
        return Collections.singleton(new AutoConfigurationPackages.PackageImport(metadata));
    }
}

@Import(Registrar.class)作用:将主配置类的所在包以及下边所有子包里面的所有组件扫描到Spring容器中。这也就能理解为什么会自动扫描我们写的@Controller类了。

@Import(AutoConfigurationImportSelector.class):进入AutoConfigurationImportSelector.class类中,查看如下方法:

public String[] selectImports(AnnotationMetadata annotationMetadata) {
    if(!this.isEnabled(annotationMetadata)) {
        return NO_IMPORTS;
    } else {
        try {
            AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
            AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
            // 主要用到的是 这个 configurations 后面会有重点说明
            List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
            configurations = this.removeDuplicates(configurations);
            configurations = this.sort(configurations, autoConfigurationMetadata);
            Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
            this.checkExcludedClasses(configurations, exclusions);
            configurations.removeAll(exclusions);
            configurations = this.filter(configurations, autoConfigurationMetadata);
            this.fireAutoConfigurationImportEvents(configurations, exclusions);
            return StringUtils.toStringArray(configurations);
        } catch (IOException var6) {
            throw new IllegalStateException(var6);
        }
    }
}

这是导入组件的选择器方法,将所有需要导入的组件以全类名的方式返回,这些组件最终被添加到容器中。其中List<String> configurations会给容器中导入非常多的自动配置类[xxxAutoConfiguration],就是给容器中导入这个场景需要的所有组件,并配置好这些组件。有了自动配置类,免去了我们手动编写配置注入功能组件等的工作;自动配置类共109个,如下部分所示:

☹ 那么我们就有疑问,这些自动配置类都是从哪里来的?
进入这个方法:this.getCandidateConfigurations(annotationMetadata, attributes)

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
    // *** 后边需要了解的方法 ***
    //SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class,classLoader);
    List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
    Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
    return configurations;
}

进入SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class,classLoader)方法,具体注释说明:

public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
    //org.springframework.context.ApplicationContextInitializer
    String factoryClassName = factoryClass.getName();
    return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
    MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader);
    if(result != null) {
        return result;
    } else {
        try {
            //通过类加载器(classLoader获取)META-INF/spring.factories(也就是配置了109个自动配置类的文件) 资源
            Enumeration<URL> urls = classLoader != null?classLoader.getResources("META-INF/spring.factories"):ClassLoader.getSystemResources("META-INF/spring.factories");
            LinkedMultiValueMap result = new LinkedMultiValueMap();

            while(urls.hasMoreElements()) {
                URL url = (URL)urls.nextElement();
                UrlResource resource = new UrlResource(url);
                //将urls 当做一个properties配置文件
                Properties properties = PropertiesLoaderUtils.loadProperties(resource);
                Iterator var6 = properties.entrySet().iterator();

                while(var6.hasNext()) {
                    Entry<?, ?> entry = (Entry)var6.next();
                    //将META-INF/spring.factories文件中的EnableAutoConfiguration下的配置进行加载   如下图所示
                    List<String> factoryClassNames = Arrays.asList(StringUtils.commaDelimitedListToStringArray((String)entry.getValue()));
                    result.addAll((String)entry.getKey(), factoryClassNames);
                }
            }

            cache.put(classLoader, result);
            return result;
        } catch (IOException var9) {
            throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var9);
        }
    }
}

我们进入其中一个自动配置类中看看SpringBoot是不是真的帮我们已经配置好了一些属性[WebMvcAutoConfiguration]:

//这里我就摘出一些重要的配置,来帮我我们观察即可。
@Configuration
public class WebMvcAutoConfiguration {
    @Bean
    @ConditionalOnMissingBean
    /** 视图解析器 , SpringBoot中的所有配置文件都是.java形式,方法的名字,就是以前xml中的id。
        等等都是用注解表示的,这个我们后面会重点说明,这里就先了解一下*/
    //我们可以看到SpringBoot已经帮我们配置好了视图解析器 等等一些功能 我们直接使用就好
    public InternalResourceViewResolver defaultViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix(this.mvcProperties.getView().getPrefix());
        resolver.setSuffix(this.mvcProperties.getView().getSuffix());
        return resolver;
    }
}

总结: SpringBoot在启动的时候从类路径下的META-INF/spring.factories中获取EnableAutoConfiguration指定的值,将这些值作为自动配置类导入到容器中,自动配置类就生效,帮我们进行自动配置工作。如此一来,就具有我们在SSM等环境下写了一大堆配置文件后才具有的功能。而这些所有配置文件都在spring-boot-autoconfigure-2.0.0.RELEASE.jar 中。

五、使用 Spring Initializer 快速创建 Spring Boot 项目

注意:Artifact中不能大小写混合使用。

通过需求选择starts,例如选择Web

我们就会发现pom.xml文件中,就会自动配置了我们引入的starts

<!-- 摘取一部分 -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>
<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>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

添加controller层: 新注解@RestController == @ResponseBody@Controller的合体;

//这个类的所有方法返回的数据直接写给浏览器(如果是对象转为JSON)
//@ResponseBody@Controller
@RestController
public class HelloWordController {
    @RequestMapping("/hello")
    public String hello(){
        return "hell";
    }
}

优点: 默认生成的SpringBoot项目,我们只需要编写自己的逻辑。默认生成的Resources配置文件的目录结构:
【1】static:保存所有的静态资源。 [js/css/image]
【2】templates:保存所有的模板页面[SpringBoot默认jar包使用嵌入式的 Tomcat,默认不支持JSP页面]但可以使用模板引擎。(freemarkerthymeleaf
【3】application.propertiesSpringBoot应用的配置文件。默认的配置都在此文件可以修改。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1227503.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Unity 场景烘培 ——unity Post-Processing后处理1(四)

提示&#xff1a;文章有错误的地方&#xff0c;还望诸位大神不吝指教&#xff01; 文章目录 前言一、Post-Processing是什么&#xff1f;二、安装使用Post-Processing1.安装Post-Processing2.使用Post-Processing&#xff08;1&#xff09;.添加Post-process Volume&#xff08…

常用组合逻辑verilog实现之8-3优先编码器

文章目录 一、问题描述二、verilog源码三、综合及仿真结果一、问题描述 本例中将实现一个8-3优先编码器。优先编码器允许多个输入信号同时有效,输出针对优先级别高的信号进行编码。 8-3优先编码器有对应的芯片实现比如TI公司的CD4532,可以从下面链接下载其手册。 CD4532数…

【C++】入门三

接下来我们说一下引用这个概念&#xff0c;那么什么是引用呢&#xff1f;简单来说引用就是取别名&#xff0c;比如有一个变量叫a&#xff0c;现在我给它取了一个别名叫b&#xff0c;那么此时a和b管理的都是一块空间 这个例子就可以很好的体现a和b管理的是同一块空间&#xff0…

ClientDateSet:Cannot perform this operation on a closed dataset

一、问题表现 Delphi 三层DataSnap&#xff0c;使用AlphaControls控件优化界面&#xff0c;一窗口编辑时&#xff0c;出现下列错误提示&#xff1a; 编译通过&#xff0c;该窗口中&#xff0c;重新显示数据&#xff0c;下图&#xff1a; 相关代码&#xff1a; procedure…

fusion 360制作机械臂

参考教程&#xff1a;Industrial Robot ( PART - 5) - FUSION 360 TUTORIAL_哔哩哔哩_bilibili

Java,集合框架,关于Map接口与Collections工具类

目录 Map接口 Map及其实现类的对比&#xff1a; HashMap中元素的特点&#xff1a; 相关方法&#xff1a; 添加、修改操作: 删除操作&#xff1a; 元素查询的操作: 元视图操作的方法&#xff1a; TreeMap的使用&#xff1a; Properties类&#xff1a; Collections工具…

【React】React 基础

1. 搭建环境 npx create-react-app react-basic-demo2. 基本使用 JSX 中使用 {} 识别 JavaScript 中的表达式&#xff0c;比如变量、函数调用、方法调用等。 if、switch、变量声明等属于语句&#xff0c;不是表达式。 列表渲染使用 map 。 事件绑定用&#xff1b;on 事件名称…

OSG加载模型时显示读取进度

目录 1. 前言 2. 开发环境说明 3. 功能实现 3.1. 方法1 3.2. 方法2 3.3. 方法3 4. 附加说明 1. 前言 OSG中加载模型文件到视景器&#xff0c;一般通过osgDB::readXXXX系列开头的函数来加载模型&#xff0c;如&#xff1a;osgDB::readNodeFile、osgDB::readImageFile、os…

055-第三代软件开发-控制台输出彩虹日志

第三代软件开发-控制台输出彩虹日志 文章目录 第三代软件开发-控制台输出彩虹日志项目介绍控制台输出彩虹日志实现原理真实代码 总结 关键字&#xff1a; Qt、 Qml、 关键字3、 关键字4、 关键字5 项目介绍 欢迎来到我们的 QML & C 项目&#xff01;这个项目结合了 QM…

MyBatis使用注解操作及XML操作

文章目录 1. 注解操作1.1 打印日志1.2 参数传递1.3 增&#xff08;Insert&#xff09;注意1&#xff1a;重命名注意2&#xff1a;返回主键 1.4 删&#xff08;Delete&#xff09;1.5 改&#xff08;Update&#xff09;1.6 查&#xff08;Select&#xff09;1. 配置&#xff0c;…

STM32串口重定向/实现不定长数据接收

STM32串口重定向/实现不定长数据接收 重定向MicroLIB 不定长数据接收 这是一期STM32内容代码分享&#xff0c;关于STM32重定向的代码和一些出现的问题吗&#xff0c;以及串口接收不定长数据思路 重定向 重定向的功能&#xff1a;能够在STM32中使用printf函数通过串口发送数据 …

最新版微信如何打开青少年模式?

最新版微信如何打开青少年模式&#xff1f; 1、将手机微信升级到最新版&#xff0c;并打开后点击底部我的进入&#xff1b; 2、在我的内&#xff0c;找到并点击设置进入&#xff1b; 3、在设置内找到青少年模式&#xff0c;并点击进入开启微信青少年模式&#xff1b; 原文来源…

【碰碰球】弹珠游戏-微信小程序项目开发流程详解

还记得小时候玩过的弹珠撞击游戏不&#xff0c;这里把它的实现原理通俗易懂地讲一下&#xff0c;看看怎样实现一个碰碰球(弹珠)小游戏&#xff0c;除了个人玩法&#xff0c;也可以双人玩哦&#xff0c;与打乒乓球一样的&#xff0c;可练习临场反应。 创建项目 打开微信开发者…

在线随机字符串生成工具

具体请前往&#xff1a;在线随机字符串生成器--通过该工具生成动态复杂随机密码,随机字符串等&#xff0c;加密盐等

特效!视频里的特效在哪制作——Adobe After Effects

今天&#xff0c;我们来谈谈一款在Adobe系列中推出的一款图形视频处理软件&#xff0c;适用于从事设计和视频特技的机构&#xff0c;包括电视台、动画制作公司、个人后期制作工作室以及多媒体工作室的属于层类型后期软件——Adobe After Effects。 Adobe After Effects&#xf…

ubuntu安装完qt后发现找不到图标

layout: post # 使用的布局&#xff08;不需要改&#xff09; title: Qt启动问题 # 标题 subtitle: ubuntu安装完Qt #副标题 date: 2023-11-18 # 时间 author: BY ThreeStones1029 # 作者 header-img: img/about_bg.jpg #这篇文章标题背景图片 catalog: true # 是否归档 tags: …

Pytest自动化测试框架:mark用法---测试用例分组执行

pytest中的mark&#xff1a; mark主要用于在测试用例/测试类中给用例打标记(只能使用已注册的标记名)&#xff0c;实现测试分组功能&#xff0c;并能和其它插件配合设置测试方法执行顺序等。 如下图&#xff0c;现在需要只执行红色部分的测试方法&#xff0c;其它方法不执行&am…

中间件安全: Apache 远程代码执行 (CVE-2021-42013)

中间件安全&#xff1a; Apache 远程代码执行 &#xff08;CVE-2021-42013&#xff09; Apache HTTP Server是美国阿帕奇&#xff08;Apache&#xff09;基金会的一款开源网页服务器。该服务器具有快速、可靠且可通过简单的API进行扩充的特点&#xff0c;发现 Apache HTTP Ser…

EEPROM与Flash的区别

EEPROM与Flash的区别 EEPROMEEPROM内部功能框图实现写入数据内部结构存储管在充电或放电状态下有着不同的阈值电压 问题点EEPROM是如何失效的呢&#xff1f;为何EEPROM不能做大呢&#xff1f; ------------------------------------------------------------------------------…

《轻松入门!快速安装PyCharm,打造高效Python编程环境》

「Pycharm安装包和相关插件&#xff08;Windows 64位&#xff09;」https://www.aliyundrive.com/s/jByv6vjShVz 提取码: 1234 视频教程&#xff1a;https://www.douyin.com/video/7303106933521763596?previous_pageapp_code_link 第一步&#xff1a;找到一起下载的Pycharm安…