search
HomeJavaJavagetting StartedWhat is the principle of spring boot?
What is the principle of spring boot?Jun 16, 2020 pm 02:14 PM
spring boot

What is the principle of spring boot?

What is the principle of spring boot:

1. Content introduction

Introduced Spring Boot through "Spring Boot Experience" What can be done? This article mainly analyzes the basic implementation ideas of its various functional points, so as to have an overall rational understanding of Spring Boot.

  • Dependency management: Spring Boot has done a lot of starters, and starters are just an entrance to help us import dependencies, simplifying project dependency management

  • Automatic configuration: Spring Boot provides configuration classes for many common components and frameworks based on Spring code configuration, thereby simplifying project configuration

  • Embedded container: Common web containers that integrate Java to simplify development Environment construction, and it is the basis for packaging plug-ins to package web applications into executable files

  • Maven plug-in: used to package jar files or war files that can be run directly, for the out-of-box project Use to provide support, and of course there are some small functions to assist development

  • Hot start: Reduce the number of repeated starts of containers during the development process and improve development efficiency

  • Application Monitoring: Provides basic services for application auditing, health monitoring, and metric data collection

  • CLI (command line tool): for rapid prototyping, there is no need to use

2. Starter dependencies: starter

In a regular Maven project, if you want to use a certain framework or component, you need to import a large number of dependencies, and you must pay attention to the version matching of the dependencies, etc. The problem is that Spring Boot provides a large number of starters. Such starters will use Maven's dependency transfer to help us import related dependencies. For example, the following pom file will add web-related dependencies, including Spring Web, Spring MVC, etc.:

    .......    <dependencies>
        <!--Web应用程序的典型依赖项-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>

    </dependencies>
    .......

Principle: We just imported a dependency , but the Dependencies use Maven's dependency transfer to help us import a large number of packages used in web development. If we decompress the file corresponding to this dependency, we find the jar file In fact, there is no substantive content in it, because it is just a pom project. The substantive content is in the file corresponding to the package, which is created by mavne Downloaded when downloading the jar file, many dependencies are declared in the file, such as: spring-webmvc, spring-web, etc.

In short, if our project depends on a certain starter, then the starter will depend on many other dependencies, and Maven's dependency transfer will add the dependencies that the starter depends on to our project. . The starter is just an import intermediary for our project dependencies.

You can refer to relevant information about maven's dependency transfer. A brief description is as follows:

Project A depends on B, and B depends on C. Project A only needs to declare that it depends on B, but does not need to declare that it depends on C. Maven automatically manages the delivery of this dependency.

2. Automatic configuration: AutoConfiguration

Spring Boot will automatically configure related components or frameworks using default values ​​​​according to certain conditions, thereby greatly reducing the project’s configuration files. It automatically scans and Added its own processing flow based on code configuration. The following content first briefly introduces Spring's code-based configuration, and then introduces what Spring Boot does.

(1) Spring code-based configuration

Before Spring3, the way to use Spring context was generally as follows:

Spring configuration file

<!-- 数据源 -->
 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
 <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
 <property name="username" value="hr" />
 <property name="password" value="hr" /></bean>
 <!--组件扫描-->
 <context:component-scan base-package="com.demo.spring.sample.step03.?rvic?" />

Business code

package com.demo.spring.sample.step03.service.impl;.......@Service("userService")
public class UserService implements IUserService {   
   @Autowired
   private IUserDAO userDAO = null;
}

Create Spring context

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

Summary:

Tell Spring to scan the class path for @Component, @Repository, @Service, @ through component-scan For classes annotated with Controller, Spring instantiates these classes and registers the instances into the Spring context. However, third-party beans such as data sources and property files are still configured using XML files. If you want to completely eliminate XML configuration files, it is still not feasible. Yes, if it must be done, it is relatively troublesome.

There are advantages and disadvantages to using XML configuration files. One of the disadvantages is that you cannot customize the bean instantiation process too much. For example, for the above dataSource, you only need to instantiate it if you want to have Oracle's jdbc driver in the class path. ation, this cannot be accomplished. Another disadvantage is that the code logic is scattered, because part of the logic is configured in XML; of course, the advantage is that the configuration is centralized and it is convenient to switch configurations.

After Spring 3, you can use the Spring container in the following way:

Spring configuration class

@Configuration // 表明当前类提供Spring配置文件的作用,Spring上下文会从当前类的注解中提取配置信息
@ComponentScan(basePackages = "com.demo.spring.sample.step08") 
// 开启组件扫描
public class AppConfig {
    @Bean // 表示这个方法实例化一个bean,id=dataSource
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(password);
        return dataSource;
    }}

Business code

package com.demo.spring.sample.step03.service.impl;.......@Service("userService")
public class UserService implements IUserService {   
   @Autowired
   private IUserDAO userDAO = null;
}

Create Spring context

ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

Summary:

XML-based configuration is no longer used when creating a Spring context. The configuration file disappears and is replaced by the AppConfig class. This class needs to be annotated with @Configuration, and this class can have @Bean annotated methods, the container will automatically call such methods to instantiate the Bean.

(2) Spring Boot's automatic configuration

Spring Boot has helped write a large number of classes annotated with @Configuration. Each class provides a component or framework configuration, such as DataSourceConfiguration. Static inner class Dbcp2 in .java, which provides configuration of DBCP data sources

//DBCP 数据源配置.
@Configuration //这个注解在实际代码中没有加,当前类被其它配置类Import
@ConditionalOnClass(org.apache.commons.dbcp2.BasicDataSource.class)
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type",  matchIfMissing = true,havingValue = "org.apache.commons.dbcp2.BasicDataSource")
static class Dbcp2 {

   @Bean
   @ConfigurationProperties(prefix = "spring.datasource.dbcp2")
   public org.apache.commons.dbcp2.BasicDataSource dataSource(
         DataSourceProperties properties) {
      return createDataSource(properties,
            org.apache.commons.dbcp2.BasicDataSource.class);
   }

}

Summary:

当Spring Boot启动的基本步骤走完后,  如果启用了自动配置,Spring Boot会加载下的文件中的内容,该文件中定义了有关自动配置的信息,其中EnableAutoConfiguration对应的每一个类中都加入了注解@Configuration,也就是说这样的每一个类都相当于Spring的一个或多个配置文件,而其中加注解@Bean的方法是bean的工厂方法,会由Spring上下文自动调用,并且将返回的对象注册到上下文中。

spring.factories文件中自动配置类的部分内容

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
......
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
......

(三)、如何覆盖自动配置的属性

Spring Boot的自动配置会采用大量的默认值(约定由于配置),可以通过在类路径下提供application.properties或者application.yml配置文件来覆盖默认值,当然部分属性值必须通过该配置文件来提供,比如如果要使用Spring Boot对数据源的自动配置,则在配置文件中必须提供jdbc的url,否则会抛出异常。

三、集成内嵌容器 :main方法

Spring Boot支持的内嵌容器Tomcat、Jetty、Undertow本身就支持在Java中内嵌使用,因为这些容器本身就是使用Java编写的,只不过Spring Boot在main方法的调用链中根据自动配置嵌入了这样的容器。

不使用这样的内嵌容器也是可以的,在Maven中移除这样的依赖就可以,当然这个时候如果要通过Spring Boot使用Web相关框架,则需要打包为war包后独立部署,或者在开发过程中使用IDE环境的开发部署功能。

不使用内嵌容器的Web应用在打包时需要对工程进行一定的修改。

四、打包可运行文件 :maven-plugin

Maven使用的默认打包工具支持打包jar文件或者war文件,但是打包后的jar文件中不能再嵌入jar文件,而打包后的war文件不能直接运行,为了把工程所有文件打包为一个可直接运行的jar文件或war文件,spring提供了一个maven插件来解决这样的问题。当然这个插件还提诸如spring-boot:run这样的开发功能

五、热启动 :devtools

在开发过程中,当完成一个功能单元后,我们会启动程序查看运行效果,如果代码需要再次修改,则修改后需要关掉程序,然后重启程序,这个过程不断迭代,从而完成代码的编写、调试。

Spring Boot 热启动通过重写容器的类加载器,完成程序的部分重启,从而简化、加速程序的调试过程。spring-boot-devtools通过两个类加载器分别加载依赖库和项目代码,当spring-boot-devtools发现项目的编译输出路径下有变化时,通过其中的一个类加载器重新加载所有的项目自有代码,从而完成热启动。这样的热启动比冷启动(关闭、重启)要快很多,到底快多少取决于项目自有代码的数量。

和热启动对应的还有一个热替换,是指单独地替换被修改的某一个class到jvm中,甚至可以单独替换class的某个方法,这种方式比热启动要快,通常使用 JavaAgent 拦截默认加载器的行为来实现,spring有个独立的项目Spring Loaded就是这么做的,但是项目已经被移到了 attic 了,也就是被Spring束之高阁,所以不建议使用。

六、应用监控:actuator

如果类路径中有actuator这个组件的话,Spring Boot的自动配置会自动创建一些端点(端点:遵循Restful设计风格的资源,对应于Controller的某一个处理请求的方法),这些端点接受请求后返回有关应用的相关信息,比如:健康信息、线程信息等。返回的是json格式的数据,而使用 Spring Boot Admin 可以实现这些 JSON 数据的视图展现,当然也可以为其他应用监控系统监控当前系统提供服务。

七、问题:

为什么pom文件中要继承spring-boot-starter-parent?

spring-boot-starter-parent是spring-boot提供的一个pom,在该pom中定义了很多属性,比如:java源文件的字符编码,编译级别等,还有依赖管理、资源定义的相关pom配置,项目的pom如果继承starter-parent,可以减少相关配置

推荐教程: 《java教程

The above is the detailed content of What is the principle of spring boot?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Spring Boot Actuator从未授权访问到getshell的示例分析Spring Boot Actuator从未授权访问到getshell的示例分析May 23, 2023 am 08:56 AM

前言部门大佬在某src上挖到了这个漏洞,是一个比较老的洞了,我觉得有点意思,就动手在本地搭了个环境测试一下。Actuator是springboot提供的用来对应用系统进行自省和监控的功能模块,借助于Actuator开发者可以很方便地对应用系统某些监控指标进行查看、统计等。在Actuator启用的情况下,如果没有做好相关权限控制,非法用户可通过访问默认的执行器端点(endpoints)来获取应用系统中的监控信息,从而导致信息泄露甚至服务器被接管的事件发生。如上所示,actuator是springb

如何利用Spring Boot构建区块链应用和智能合约如何利用Spring Boot构建区块链应用和智能合约Jun 22, 2023 am 09:33 AM

随着比特币等数字货币的兴起,区块链技术也逐渐成为热门话题。而智能合约,则可视为区块链技术的重要组成部分。SpringBoot作为一种流行的Java后端开发框架,也能够用来构建区块链应用和智能合约。本文将介绍如何利用SpringBoot搭建基于区块链技术的应用和智能合约。一、SpringBoot与区块链首先,我们需要了解一些与区块链相关的基本概念。区块链

基于Spring Boot和MyBatis Plus实现ORM映射基于Spring Boot和MyBatis Plus实现ORM映射Jun 22, 2023 pm 09:27 PM

在Javaweb应用开发过程中,ORM(Object-RelationalMapping)映射技术用来将数据库中的关系型数据映射到Java对象中,方便开发者进行数据访问和操作。SpringBoot作为目前最流行的Javaweb开发框架之一,已经提供了集成MyBatis的方式,而MyBatisPlus则是在MyBatis的基础上扩展的一种ORM框架。

使用Spring Boot和Apache ServiceMix构建ESB系统使用Spring Boot和Apache ServiceMix构建ESB系统Jun 22, 2023 pm 12:30 PM

随着现代企业越来越依赖于各种不同的应用程序和系统,企业集成变得愈发重要。企业服务总线(ESB)就是一种集成架构模式,通过将不同系统和应用程序连接在一起,提供通用的数据交换和消息路由服务,从而实现企业级应用程序集成。使用SpringBoot和ApacheServiceMix,我们可以轻松构建一个ESB系统,这篇文章将介绍如何实现。SpringBoot和A

基于Spring Boot的分布式数据缓存和存储系统基于Spring Boot的分布式数据缓存和存储系统Jun 22, 2023 am 09:48 AM

随着互联网的不断发展和普及,数据的处理和存储需求也越来越大,如何高效且可靠地处理和存储数据成为了业界和研究人员的热门话题。基于SpringBoot的分布式数据缓存和存储系统是近年来备受关注的一种解决方案。什么是分布式数据缓存和存储系统?分布式数据缓存和存储系统是指通过多个节点(服务器)分布式地存储数据,提高了数据的安全性和可靠性,同时也可以提升数据的处理性

Spring Boot与NoSQL数据库的整合使用Spring Boot与NoSQL数据库的整合使用Jun 22, 2023 pm 10:34 PM

随着互联网的发展,大数据分析和实时信息处理成为了企业的一个重要需求。为了满足这样的需求,传统的关系型数据库已经不再满足业务和技术发展的需要。相反,使用NoSQL数据库已经成为了一个重要的选择。在这篇文章中,我们将讨论SpringBoot与NoSQL数据库的整合使用,以实现现代应用程序的开发和部署。什么是NoSQL数据库?NoSQL是notonlySQL

使用Spring Boot和JavaFX构建桌面应用程序使用Spring Boot和JavaFX构建桌面应用程序Jun 22, 2023 am 10:55 AM

随着技术的不断发展,我们现在可以使用不同的技术来构建桌面应用程序。而SpringBoot和JavaFX则是现在较为流行的选择之一。本文将重点介绍如何使用这两个框架来构建一个功能丰富的桌面应用程序。一、介绍SpringBoot和JavaFXSpringBoot是一个基于Spring框架的快速开发框架。它可以帮助开发者快速构建Web应用程序,同时提供一组开

Spring Boot的任务调度和定时任务实现方法Spring Boot的任务调度和定时任务实现方法Jun 22, 2023 pm 11:58 PM

SpringBoot是一款非常流行的Java开发框架,不仅具有快速开发的优势,而且还内置了很多实用的功能,其中,任务调度和定时任务就是其常用的功能之一。本文将探讨SpringBoot的任务调度和定时任务实现方法。一、SpringBoot任务调度简介SpringBoot任务调度(TaskScheduling)是指在特定的时间点或某个条件下,执行一些特

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor