Java 自定义回调函数

1. 先定义一个回调接口

package com.JXWork.service;

/**
 * 自定义回调接口
 */
public interface LJCallBack {

    void handler(String message);
}

2.  测试回调方法

    /**
     * 方法执行完毕时,通过回调函数打印Message
     * @param callback
     */

    public void sayHello(LJCallBack callback) {

        int count = 0;
        while(count <= 100) {
            count++;
        }
        callback.handler("sayHello over!");
    }

    /**
     * 单元测试,直接调用sayHello方法
     * 打印:sayHello over!
     */
    @Test
    public void callBackTest() {

        sayHello(new LJCallBack() {
            @Override
            public void handler(String message) {
                System.out.println(message);
            }
        });
    }

3. 输出测试结果:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Spring Boot 中,可以通过自定义回调函数来实现在应用程序启动或停止时执行特定的操作。 首先,需要实现 `ApplicationRunner` 或 `CommandLineRunner` 接口,并实现其 `run` 方法。`ApplicationRunner` 接口提供了一个 `ApplicationArguments` 参数,可以获取应用程序启动时传递的参数。而 `CommandLineRunner` 接口则提供了一个字符串数组参数,可以获取命令行参数。 例如,下面是一个实现 `ApplicationRunner` 接口的示例: ```java @Component public class MyApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { // 在应用程序启动时执行的操作 System.out.println("Application started with arguments: " + args); } } ``` 或者,下面是一个实现 `CommandLineRunner` 接口的示例: ```java @Component public class MyCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { // 在应用程序启动时执行的操作 System.out.println("Application started with arguments: " + Arrays.toString(args)); } } ``` 这些自定义回调函数将在 Spring Boot 应用程序启动时自动执行。如果需要在应用程序停止时执行操作,可以使用 `@PreDestroy` 注解标记一个方法,它将在 Spring 容器关闭之前执行。 例如,下面是一个在应用程序停止时执行操作的示例: ```java @Component public class MyShutdownHook { @PreDestroy public void onShutdown() throws Exception { // 在应用程序停止时执行的操作 System.out.println("Application stopped"); } } ``` 这些自定义回调函数可以帮助您在 Spring Boot 应用程序启动或停止时执行特定的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值