gpt4 book ai didi

java - 回调是什么意思?

转载 作者:行者123 更新时间:2023-12-01 08:00:43 25 4
gpt4 key购买 nike

我正在阅读 spring 文档。我一直听到“回调”这个词。例如:生命周期回调初始化回调等

我们如何理解回调函数?当你在 Spring 说“生命周期回调”时,它是什么意思?

我一直在努力理解这一点,但我不确定我是否理解正确。请帮忙。

最佳答案

生命周期

在 Spring beans 的上下文中(我相信这是您正在阅读的内容的上下文 - 很难用您提供的少量信息来判断),bean 会经历不同的生命周期阶段(例如创建和销毁)。以下是您可以 Hook 的 Spring bean 的生命周期阶段:

enter image description here

回调

@R.T. 的 wikipedia 链接指向什么是回调,是理解回调的一个很好的起点。在Java中,回调的概念有不同的实现方式。

In object-oriented programming languages without function-valued arguments, such as in Java before its 1.7 version, callbacks can be simulated by passing an instance of an abstract class or interface, of which the receiver will call one or more methods, while the calling end provides a concrete implementation.

@SotiriosDelamanolis 在 this answer 中给出了一个很好的例子,我将其发布在这里只是为了了解上下文。

/**
* @author @SotiriosDelamanolis
* see https://stackoverflow.com/a/19405498/2587435
*/
public class Test {
public static void main(String[] args) throws Exception {
new Test().doWork(new Callback() { // implementing class
@Override
public void call() {
System.out.println("callback called");
}
});
}

public void doWork(Callback callback) {
System.out.println("doing work");
callback.call();
}

public interface Callback {
void call();
}
}

生命周期回调

通过查看上图,您可以看到 Spring 允许您通过一些接口(interface)和注释来 Hook bean 生命周期。例如

Hook 生命周期的 bean 创建部分,您可以实现 InitializingBean,它具有回调方法 afterPropertiesSet()。当您实现此接口(interface)时,Spring 会接收它并调用 afterPropertiesSet()

例如

public class SomeBean implements InitializingBean {
@Override
public void afterPropertiesSet() { // this is the callback method
// for the bean creation phase of the
// spring bean lifecycle
// do something after the properties are set during bean creation
}
}

或者,您可以将 @PostConstruct 方法用于非 InitializingBean 实现的方法,或者在 xml 配置中使用 init-method

该图显示了您可以 Hook 并为其提供“回调”方法的其他生命周期阶段。生命周期阶段在图表顶部标有下划线

您可以在Spring reference - Lifecycle Callbacks查看更多信息

关于java - 回调是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25469369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com