search
HomeJavajavaTutorialHow to implement SpringBoot automatic configuration

    How to implement springboot

    In the previous helloworld example, I have initially experienced the ease of springboot automatically importing dependencies and completing configuration. .

    So, how is springboot implemented?

    1. Dependency Management Features

    First look at the pom.xml in the previous content example:

    <!--导入父工程-->
      <parent>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-parent</artifactId>
          <version>2.3.4.RELEASE</version>
      </parent>
      <dependencies>
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-web</artifactId>
          </dependency>
      </dependencies>

    A parent project is added here, and only one is imported. Relying on spring-boot-starter-web, all our related packages finally come in.

    How to implement SpringBoot automatic configuration

    During the whole process, there is no need to worry about the package introduction issue.

    1. Parent project

    Every springboot project has a parent project, which is generally used for dependency management.

    The parent project may declare many dependencies, so as long as the sub-project inherits the parent project, there is no need to add a version number when adding dependencies later.

    Taking the above as an example, the parent project uses the springboot version of 2.3.4.RELEASE, so there is no need to write the version number for the dependencies added below.

    (1) How the parent project manages versions

    You can hold down ctrl and click on the parent project to find out.

    How to implement SpringBoot automatic configuration

    #After coming in, I found that he also has a parent project spring-boot-dependencies.

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

    Continue to enter spring-boot-dependencies, and you can see a properties tag below:

    How to implement SpringBoot automatic configuration

    This almost declares all the possibilities we have in development The version of the jar package that will be used.

    Continue down to see the specific dependency management dependencyManagement. The version quoted here is the version declared in the properties.

    How to implement SpringBoot automatic configuration

    For example:

    On the left I saw a package called logback, so I searched inside and found that the version defined here is 1.2.3.

    How to implement SpringBoot automatic configuration

    So, the main function of the parent project is dependency management, which almost declares the version numbers of dependencies commonly used in development.

    (2) Use the specified version

    If you do not want to use the automatically arbitrated version, you can also use the specified version.

    For example, for mysql version, the result of automatic arbitration is 8.0.21, but I only want to use version 5.1.43.

    How to implement SpringBoot automatic configuration

    Add a properties tag and declare the version in it.

    <properties>
          <mysql.version>5.1.43</mysql.version>
      </properties>

    Look at the imported dependencies again and it has become the specified version.

    How to implement SpringBoot automatic configuration

    2. Scenario starter

    Let’s look at the first imported dependency spring-boot-starter-web:

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

    You will see more starters named spring-boot-starter in the future. There are also detailed instructions in the official documents

    How to implement SpringBoot automatic configuration

    What is a starter?

    starter is a set of dependency descriptions, that is, usually we only need to introduce a starter, and then the corresponding entire development scenario will be introduced.

    For example, if you want to start using Spring and JPA for database access, then introduce the spring-boot-starter-data-jpa dependency into the project.

    In addition, note that spring-boot-starter-* here is the official starter naming method.

    So there are still unofficial ones? Yes, if you feel that the official starter scenario still cannot meet your needs, you can customize the starter.

    But the official recommendation is to use thirdpartyproject-spring-boot-starter for customized naming.

    As for why only one starter can import the dependencies of the entire scene, it is actually the same dependency feature of maven as the parent project above.

    Enter spring-boot-starter-web, scroll down, and you can see the dependencies used in developing web scenarios.

    How to implement SpringBoot automatic configuration

    #So, for which scenario you need to develop in the future, just refer to the official documentation and import the corresponding launcher.

    2. Automatic configuration

    Let’s review what springboot automatically configured in the previous helloworld project:

    • Automatically configure tomcat

    • Automatically configure springMVC

    • Automatically configure common web functions, such as: character encoding issues

    • 默认的包结构:主程序所在包以及下面所有子包里的组件都会被默认扫描

    • 各种配置拥有默认值

    • 按需加载所有自动配置项

    • ......

    1. 自动配置组件

    不管自动配置好什么,步骤都是:先引入、再配置。

    比如 tomcat,那么前提是先引入了 tomcat 依赖,这就由上面第一部分内容所讲的依赖管理完成,在引入了 web starter 后,自动引入场景。

    自动引入了场景,也就引入了这个场景下所用到的各种 jar 包,接下来就是要配置这些内容,比如 tomcat、springMVC 等等。

    拿 springMVC 举例,在之前要使用 springMVC,肯定要配置DispatcherServlet,帮我们拦截所有请求。

    <servlet>
            <servlet-name>springMVC</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springMVC.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>

    现在看下之前的 helloworld 应用中,springboot 是在哪里帮我们做好配置的。

    先看主程序类:

    // 标记这是一个 springboot应用,这个类是主程序类,所有启动的入口
    @SpringBootApplication
    public class MainApplication {
        public static void main(String[] args) {
            SpringApplication.run(MainApplication.class, args);
        }
    }

    可以创建个本地变量(alt+enter),可以看到这个是个ConfigurableApplicationContext类型。

    How to implement SpringBoot automatic configuration

    @SpringBootApplication
    public class MainApplication {
        public static void main(String[] args) {
            ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
        }
    }

    可以使用getBeanDefinitionNames()方法,查看里面包含了哪些容器,遍历打印出来。

    @SpringBootApplication
    public class MainApplication {
        public static void main(String[] args) {
            // 返回IOC容器
            final ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
            // 查看容器里的组件
            final String[] beanDefinitionNames = run.getBeanDefinitionNames();
            for (String name: beanDefinitionNames) {
                System.out.println(name);
            }
        }
    }

    接下来启动应用,看下控制台输出。

    How to implement SpringBoot automatic configuration

    在控制台输出里ctrl+F搜索下DispatcherServlet:

    How to implement SpringBoot automatic configuration

    发现 IOC 容器中已经有了对应的组件。

    2. 默认的包结构

    主程序所在包以及下面所有子包里的组件都会被默认扫描,所以我们不需要配置开启组件扫描,也可以正常使用。

    但是要注意这里的范围:

    How to implement SpringBoot automatic configuration

    示例中就是com.pingguo.boot包下以及所有子包都可以自动扫描。

    如果你就是要放到外面,还希望被扫描到,怎么办?

    那么可以使用主程序类中@SpringBootApplication注解中的一个属性scanBasePackages,扩大包的范围即可:

    @SpringBootApplication(scanBasePackages = "com.pingguo")
    public class MainApplication {
        public static void main(String[] args) {
    ... ...
    3. 各种配置拥有默认值

    比如 tomcat端口,在application.properties配置文件里使用 idea 输入的时候,就可以看到带有默认值8080:

    How to implement SpringBoot automatic configuration

    点击进去可看到后面都是绑定了对应的 java 类。

    How to implement SpringBoot automatic configuration

    配置文件的值最终会绑定在对应的类上,这个类会在容器中创建对象。

    4. 按需加载所有自动配置项

    比如应用中只引入了spring-boot-starter-web,那么就只有web场景的自动配置才会开启。

    springboot 中的所有自动配置,都在这里:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
        <version>2.3.4.RELEASE</version>
        <scope>compile</scope>
      </dependency>

    点击spring-boot-starter-web可以找到spring-boot-starter,再进入其中就可以看到spring-boot-autoconfigure。

    The above is the detailed content of How to implement SpringBoot automatic configuration. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    怎么使用SpringBoot+Canal实现数据库实时监控怎么使用SpringBoot+Canal实现数据库实时监控May 10, 2023 pm 06:25 PM

    Canal工作原理Canal模拟MySQLslave的交互协议,伪装自己为MySQLslave,向MySQLmaster发送dump协议MySQLmaster收到dump请求,开始推送binarylog给slave(也就是Canal)Canal解析binarylog对象(原始为byte流)MySQL打开binlog模式在MySQL配置文件my.cnf设置如下信息:[mysqld]#打开binloglog-bin=mysql-bin#选择ROW(行)模式binlog-format=ROW#配置My

    Spring Boot怎么使用SSE方式向前端推送数据Spring Boot怎么使用SSE方式向前端推送数据May 10, 2023 pm 05:31 PM

    前言SSE简单的来说就是服务器主动向前端推送数据的一种技术,它是单向的,也就是说前端是不能向服务器发送数据的。SSE适用于消息推送,监控等只需要服务器推送数据的场景中,下面是使用SpringBoot来实现一个简单的模拟向前端推动进度数据,前端页面接受后展示进度条。服务端在SpringBoot中使用时需要注意,最好使用SpringWeb提供的SseEmitter这个类来进行操作,我在刚开始时使用网上说的将Content-Type设置为text-stream这种方式发现每次前端每次都会重新创建接。最

    SpringBoot怎么实现二维码扫码登录SpringBoot怎么实现二维码扫码登录May 10, 2023 pm 08:25 PM

    一、手机扫二维码登录的原理二维码扫码登录是一种基于OAuth3.0协议的授权登录方式。在这种方式下,应用程序不需要获取用户的用户名和密码,只需要获取用户的授权即可。二维码扫码登录主要有以下几个步骤:应用程序生成一个二维码,并将该二维码展示给用户。用户使用扫码工具扫描该二维码,并在授权页面中授权。用户授权后,应用程序会获取一个授权码。应用程序使用该授权码向授权服务器请求访问令牌。授权服务器返回一个访问令牌给应用程序。应用程序使用该访问令牌访问资源服务器。通过以上步骤,二维码扫码登录可以实现用户的快

    SpringBoot/Spring AOP默认动态代理方式是什么SpringBoot/Spring AOP默认动态代理方式是什么May 10, 2023 pm 03:52 PM

    1.springboot2.x及以上版本在SpringBoot2.xAOP中会默认使用Cglib来实现,但是Spring5中默认还是使用jdk动态代理。SpringAOP默认使用JDK动态代理,如果对象没有实现接口,则使用CGLIB代理。当然,也可以强制使用CGLIB代理。在SpringBoot中,通过AopAutoConfiguration来自动装配AOP.2.Springboot1.xSpringboot1.xAOP默认还是使用JDK动态代理的3.SpringBoot2.x为何默认使用Cgl

    spring boot怎么对敏感信息进行加解密spring boot怎么对敏感信息进行加解密May 10, 2023 pm 02:46 PM

    我们使用jasypt最新版本对敏感信息进行加解密。1.在项目pom文件中加入如下依赖:com.github.ulisesbocchiojasypt-spring-boot-starter3.0.32.创建加解密公用类:packagecom.myproject.common.utils;importorg.jasypt.encryption.pbe.PooledPBEStringEncryptor;importorg.jasypt.encryption.pbe.config.SimpleStrin

    使用Java SpringBoot集成POI实现Word文档导出使用Java SpringBoot集成POI实现Word文档导出Apr 21, 2023 pm 12:19 PM

    知识准备需要理解ApachePOI遵循的标准(OfficeOpenXML(OOXML)标准和微软的OLE2复合文档格式(OLE2)),这将对应着API的依赖包。什么是POIApachePOI是用Java编写的免费开源的跨平台的JavaAPI,ApachePOI提供API给Java程序对MicrosoftOffice格式档案读和写的功能。POI为“PoorObfuscationImplementation”的首字母缩写,意为“简洁版的模糊实现”。ApachePOI是创建和维护操作各种符合Offic

    springboot怎么整合shiro实现多验证登录功能springboot怎么整合shiro实现多验证登录功能May 10, 2023 pm 04:19 PM

    1.首先新建一个shiroConfigshiro的配置类,代码如下:@ConfigurationpublicclassSpringShiroConfig{/***@paramrealms这儿使用接口集合是为了实现多验证登录时使用的*@return*/@BeanpublicSecurityManagersecurityManager(Collectionrealms){DefaultWebSecurityManagersManager=newDefaultWebSecurityManager();

    springboot怎么配置mybatis和事务管理springboot怎么配置mybatis和事务管理May 10, 2023 pm 07:13 PM

    一、springboot与mybatis的配置1.首先,springboot配置mybatis需要的全部依赖如下:org.springframework.bootspring-boot-starter-parent1.5.1.RELEASEorg.springframework.bootspring-boot-starter-web1.5.1.RELEASEorg.mybatis.spring.bootmybatis-spring-boot-starter1.2.0com.oracleojdbc

    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)
    2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools