Home  >  Article  >  Java  >  What is the principle of spring boot?

What is the principle of spring boot?

hzc
hzcOriginal
2020-06-16 14:14:357262browse

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 eec96f44c7c1be047b36f06c1ea837e7, 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 35ffd8e0928e307213da87b63bd3711a 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 af26ebdadc0a793eec8fe280ca9c1087 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会加载50d40f95c57eb2493885ff1d73d54fff下的24f1ab0d6dc6fb50ace902cbd083b53c文件中的内容,该文件中定义了有关自动配置的信息,其中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