java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Springboot 启动初始化资源

Springboot 启动之后初始化资源的几种方法

作者:梅西爱骑车

在我们实际工作中,总会遇到这样需求,在项目启动的时候需要做一些初始化的操作,比如初始化线程池,提前加载好加密证书等,本文主要介绍了Springboot 启动之后初始化资源的几种方法,感兴趣的可以了解一下

假设有这么一个需求,要求在项目启动过程中,完成线程池的初始化,加密证书加载等功能,你会怎么做?如果没想好答案,请接着往下看。

今天介绍几种在Spring Boot中进行资源初始化的方式:

代码

pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.erbadagang.setup.init</groupId>
    <artifactId>setup-init</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>setup-init</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.0.RELEASE</spring-boot.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.properties

spring.application.name=setup-init
management.endpoints.jmx.exposure.include=*
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
# spring cloud access&secret config
# 可以访问如下地址查看: https://usercenter.console.aliyun.com/#/manage/ak
alibaba.cloud.access-key=****
alibaba.cloud.secret-key=****
# 应用服务 WEB 访问端口
server.port=8080
# Actuator Web 访问端口
management.server.port=8081

启动类SetupInitApplication

package com.erbadagang.setup.init.setupinit;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SetupInitApplication {

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

}

模拟一个被初始化方法调用的Service

package com.erbadagang.setup.init.setupinit.service;

import org.springframework.stereotype.Service;

/**
 * MyService作用是:模拟一个service被springboot初始化代码调用。
 *
 * @ClassName: MyService
 * @author: 郭秀志 jbcode@126.com
 * @date: 2020/6/26 16:42
 * @Copyright:
 */
@Service
public class MyService {
    public String getName() {
        return "guoxiuzhi";
    }
}

核心的启动初始化操作类SetupInit和DefaultApplicationRunner

package com.erbadagang.setup.init.setupinit.init;

import com.erbadagang.setup.init.setupinit.service.MyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * StartUpInit作用是:演示如下几种初始化方法
 *
 * @ClassName: StartUpInit
 * @author: 郭秀志 jbcode@126.com
 * @date: 2020/6/26 17:14
 * @Copyright:
 */
@Slf4j
@Component
public class SetupInit {

    @Autowired
    private MyService service;

    @PostConstruct
    public void init() {
        log.info(">>>>>分割线>>>>>");
        log.info(" @PostConstruct 初始化开始");
        log.info(service.getName() + " from PostConstruct");
    }

    /**
     * ApplicationReadyEvent 事件监听当ApplicationReady后执行。
     *
     * @param event
     */
    @EventListener
    public void handleApplicationReady(ApplicationReadyEvent event) {
        log.info(">>>>>分割线>>>>>");
        log.info("The application is ready, 初始化开始");
        log.info(service.getName() + " from ApplicationReadyEvent");
    }

    @Bean(initMethod = "init")
    public InitMethodBean initMethodBean() {
        return new InitMethodBean();
    }

    class InitMethodBean {
        @Autowired
        private MyService service;

        void init() {
            log.info(">>>>>分割线>>>>>");
            log.info(service.getName() + " from InitMethodBean");
        }

        public String getServiceName() {
            return service.getName() + " from the method 'getServiceName' of autowired Bean";
        }
    }
}

DefaultApplicationRunner

package com.erbadagang.setup.init.setupinit.init;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @description 应用启动时读取传入参数
 * @ClassName: DefaultApplicationRunner
 * @author: 郭秀志 jbcode@126.com
 * @date: 2020/6/26 19:27
 * @Copyright:
 */
@Slf4j
@Component
public class DefaultApplicationRunner implements ApplicationRunner, Ordered {

    @Autowired
    private SetupInit.InitMethodBean initMethodBean;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        log.info("i am applicationRunner! invoke the bean method:" + initMethodBean.getServiceName());

        args.getOptionNames().forEach(System.out::println);
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>");
        String[] sourceArgs = args.getSourceArgs();

        if (sourceArgs != null) {
            for (String sourceArg : sourceArgs) {
                System.out.println("sourceArg = " + sourceArg);
            }
        }


        log.info("<<<<<<<<<<<KV对参数<<<<<<<<<<<<<<");
        List<String> foo = args.getOptionValues("dev.name");
        if (!CollectionUtils.isEmpty(foo)) {
            foo.forEach(System.out::println);
        }

        log.info("++++++单身狗参数++++++");
        List<String> nonOptionArgs = args.getNonOptionArgs();
        log.info("nonOptionArgs.size() = " + nonOptionArgs.size());
        nonOptionArgs.forEach(System.out::println);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 65;
    }
}

参数准备

通过如图的位置Program arguments配置启动Springboot应用的入参:单身汪 single dog --foo=bar --dev.name=郭秀志。

多种形式的系统启动入参

执行

控制台输出如下信息,可以看到各种初始化方式的执行顺序。

2020-06-27 17:38:01.485  INFO 5340 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-06-27 17:38:01.500  INFO 5340 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-06-27 17:38:01.500  INFO 5340 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.35]
2020-06-27 17:38:01.585  INFO 5340 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-06-27 17:38:01.585  INFO 5340 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 863 ms
2020-06-27 17:38:01.616  INFO 5340 --- [           main] c.e.setup.init.setupinit.init.SetupInit  : >>>>>分割线>>>>>
2020-06-27 17:38:01.616  INFO 5340 --- [           main] c.e.setup.init.setupinit.init.SetupInit  :  @PostConstruct 初始化开始
2020-06-27 17:38:01.616  INFO 5340 --- [           main] c.e.setup.init.setupinit.init.SetupInit  : guoxiuzhi from PostConstruct
2020-06-27 17:38:01.616  INFO 5340 --- [           main] c.e.setup.init.setupinit.init.SetupInit  : >>>>>分割线>>>>>
2020-06-27 17:38:01.616  INFO 5340 --- [           main] c.e.setup.init.setupinit.init.SetupInit  : guoxiuzhi from InitMethodBean
2020-06-27 17:38:01.717  INFO 5340 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-06-27 17:38:01.857  INFO 5340 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-06-27 17:38:01.857  INFO 5340 --- [           main] c.e.s.i.setupinit.SetupInitApplication   : Started SetupInitApplication in 1.383 seconds (JVM running for 1.996)
2020-06-27 17:38:01.857  INFO 5340 --- [           main] c.e.s.i.s.init.DefaultApplicationRunner  : i am applicationRunner! invoke the bean method:guoxiuzhi from the method 'getServiceName' of autowired Bean
dev.name
foo
>>>>>>>>>>>>>>>>>>>>>>>>>>
sourceArg = 单身汪
sourceArg = single
sourceArg = dog
sourceArg = --foo=bar
sourceArg = --dev.name=郭秀志
2020-06-27 17:38:01.857  INFO 5340 --- [           main] c.e.s.i.s.init.DefaultApplicationRunner  : <<<<<<<<<<<KV对参数<<<<<<<<<<<<<<
郭秀志
2020-06-27 17:38:01.857  INFO 5340 --- [           main] c.e.s.i.s.init.DefaultApplicationRunner  : ++++++单身狗参数++++++
2020-06-27 17:38:01.857  INFO 5340 --- [           main] c.e.s.i.s.init.DefaultApplicationRunner  : nonOptionArgs.size() = 3
单身汪
single
dog
2020-06-27 17:38:01.857  INFO 5340 --- [           main] c.e.setup.init.setupinit.init.SetupInit  : >>>>>分割线>>>>>
2020-06-27 17:38:01.857  INFO 5340 --- [           main] c.e.setup.init.setupinit.init.SetupInit  : The application is ready, 初始化开始
2020-06-27 17:38:01.857  INFO 5340 --- [           main] c.e.setup.init.setupinit.init.SetupInit  : guoxiuzhi from ApplicationReadyEvent
综上,使用 @PostConstruct 注解进行初始化操作的顺序是最快的,前提是这些操作不能依赖于其它Bean的初始化完成。通过添加 @Order 注解,我们可以改变同层级之间不同Bean的加载顺序。

源代码

本文源代码可以从Gitee仓库下载

到此这篇关于Springboot 启动之后初始化资源的几种方法的文章就介绍到这了,更多相关Springboot 启动初始化资源内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文