SpringBoot启动后暴露接口 或 停止前销毁资源

SpringBoot程序启动后回调方法 ——ApplicationRunner.run()

注: CommandLineRunner同样也可以实现这个功能,区别是run()方法的参数不同

package org.springframework.boot;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

/**
 * Interface used to indicate that a bean should <em>run</em> when it is contained within
 * a {@link SpringApplication}. Multiple {@link ApplicationRunner} beans can be defined
 * within the same application context and can be ordered using the {@link Ordered}
 * interface or {@link Order @Order} annotation.
 *
 * @author Phillip Webb
 * @since 1.3.0
 * @see CommandLineRunner
 */
@FunctionalInterface
public interface ApplicationRunner {

    /**
     * Callback used to run the bean.
     * @param args incoming application arguments
     * @throws Exception on error
     */
    void run(ApplicationArguments args) throws Exception;

}

使用

package com.example.config;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class AfterRun implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("----------SpringBoot启动完成之后再做一些自己的业务-------------");
    }
}

SpringBoot程序停止前销毁资源回调方法——DisposableBean.destroy()

package org.springframework.beans.factory;

/**
 * Interface to be implemented by beans that want to release resources on destruction.
 * A {@link BeanFactory} will invoke the destroy method on individual destruction of a
 * scoped bean. An {@link org.springframework.context.ApplicationContext} is supposed
 * to dispose all of its singletons on shutdown, driven by the application lifecycle.
 *
 * <p>A Spring-managed bean may also implement Java's {@link AutoCloseable} interface
 * for the same purpose. An alternative to implementing an interface is specifying a
 * custom destroy method, for example in an XML bean definition. For a list of all
 * bean lifecycle methods, see the {@link BeanFactory BeanFactory javadocs}.
 *
 * @author Juergen Hoeller
 * @since 12.08.2003
 * @see InitializingBean
 * @see org.springframework.beans.factory.support.RootBeanDefinition#getDestroyMethodName()
 * @see org.springframework.beans.factory.config.ConfigurableBeanFactory#destroySingletons()
 * @see org.springframework.context.ConfigurableApplicationContext#close()
 */
public interface DisposableBean {

    /**
     * Invoked by the containing {@code BeanFactory} on destruction of a bean.
     * @throws Exception in case of shutdown errors. Exceptions will get logged
     * but not rethrown to allow other beans to release their resources as well.
     */
    void destroy() throws Exception;

}

使用

package com.example.config;


import org.springframework.beans.factory.DisposableBean;

import org.springframework.stereotype.Component;


@Component

public class BeforeDestroy implements DisposableBean {

    @Override

    public void destroy() throws Exception {

        System.out.println("----------SpringBoot停止前释放资源-------------");

    }

}

测试:

java -jar test-1.0-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.6.RELEASE)

2022-02-12 16:12:09.293  INFO 18967 --- [           main] com.example.App                          : Starting App v1.0-SNAPSHOT on admin with PID 18967 (G:\workspace\test\
target\test-1.0-SNAPSHOT.jar started by admin in D:\workspace\test\target)
2022-02-12 16:12:09.300  INFO 18967 --- [           main] com.example.App                          : No active profile set, falling back to default profiles: default
2022-02-12 16:12:13.231  INFO 18967 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-02-12 16:12:13.262  INFO 18967 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-02-12 16:12:13.262  INFO 18967 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.33]
2022-02-12 16:12:13.545  INFO 18967 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-02-12 16:12:13.545  INFO 18967 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 4063 ms
2022-02-12 16:12:14.235  INFO 18967 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2022-02-12 16:12:14.759  INFO 18967 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-02-12 16:12:14.764  INFO 18967 --- [           main] com.example.App                          : Started App in 6.719 seconds (JVM running for 7.785)
----------SpringBoot启动完成之后再做一些自己的业务-------------
2022-02-12 16:12:30.264  INFO 18967 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-02-12 16:12:30.265  INFO 18967 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2022-02-12 16:12:30.290  INFO 18967 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 25 ms
----------do----------
----------do----------

//此处ctrl+c停止程序
2022-02-12 16:12:37.898  INFO 18967 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
----------SpringBoot停止前释放资源-------------


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值