You need to enable JavaScript to run this app. 如何从废弃Supervisor.spec迁移至新版Supervisor.behaviour?
优惠活动
大模型
产品
解决方案
定价
更多

如何从废弃Supervisor.spec迁移至新版Supervisor.behaviour?

修改后的代码实现
defmodule A.Server do
  use Supervisor

  alias B

  def start_link(opts \\ []) do
    Supervisor.start_link(__MODULE__, opts, name: __MODULE__)
  end

  @impl true
  def init(_init_arg) do
    children = [B]
    Supervisor.init(children, strategy: :one_for_one)
  end
end
关键改动说明
  • 替换废弃的supervise/2宏:原有的宏调用已被官方移除,现在统一使用Supervisor.init/2完成监督树的初始化配置,两个接口的传参逻辑完全对齐,不需要额外调整参数格式。同时将init的参数名改为下划线开头的_init_arg,匹配不需要使用启动参数的场景,消除编译器的未使用变量警告。
  • 补充@impl true注解:明确标记init/1是Supervisor行为要求的回调函数,可在写错方法名、参数个数时提前触发编译提示,减少运行时错误。
  • 规范start_link的参数定义:增加默认空参数列表的写法,兼容后续传入自定义启动配置的扩展需求。
关于start_child接口的误区澄清

Supervisor.start_child/3是动态新增子进程场景下才会使用的接口,用于在监督树启动完成后,手动追加要被监督的进程。你的需求是在监督树初始化阶段就静态启动并托管B进程,完全不需要用到这个接口,静态配置的子进程直接写入children列表即可。

扩展用法

如果启动B进程时需要传入自定义参数,只需要调整children列表的条目格式即可,不需要手写完整的子进程规范:

# 给B传入启动参数(该参数会原样传入B的start_link函数)
children = [{B, your_startup_arg}]

如果需要自定义子进程的重启策略、关闭超时时间等特殊配置,可直接编写完整的子进程规范:

children = [
  %{
    id: B,
    start: {B, :start_link, [your_startup_arg]},
    restart: :transient,
    shutdown: 1000
  }
]

内容的提问来源于stack exchange,提问作者Flame_Phoenix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.09 09:15:11