Dagger2 子组件的 Spring DI 等价物是什么

What is the Spring DI equivalent of Dagger2 Subcomponents

Dagger2 有子组件 https://medium.com/tompee/dagger-2-scopes-and-subcomponents-d54d58511781 用于使用生命周期比主应用程序更短的 DI,例如,如果您有作业服务,那么该服务将为每个作业提供一个包含子组件的组件。

Spring 的 DI 框架的等价物是什么?

我能看到的唯一可能性是使用上下文层次结构并手动处理生命周期较短的上下文。

// Does Dagger's @Subcomponent.Factory work
public class JobExecutor {
    private final ApplicationContext mainApplicationContext;

    @Inject
    public JobExecutor(ApplicationContext mainApplicationContext) {
        this.mainApplicationContext = mainApplicationContext;
    }

    public Result execute(Job job) {
        AnnotationConfigApplicationContext jobContext = null;
        try {
            jobContext = new AnnotationConfigApplicationContext();
            jobContext.setParent(mainApplicationContext); // Provides access to common beans
            jobContext.register(SpringJobContext.class);
            jobContext.getBeanFactory().registerSingleton("job", job); // Does Dagger's @BindsInstance work
            jobContext.refresh();
            // You can access and execute one of the beans from jobContext manually or use @PostConstruct
            return jobContext.getBean(JobExecutorFromJobContext.class)
                    .execute();
        } finally {
            if (jobContext != null) {
                jobContext.destroy();
            }
        }
    }

    static class JobExecutorFromJobContext {
        private final Database database; // From parent's context
        private final Job job;

        @Inject
        JobExecutorFromJobContext(Database database, Job job) {
            this.database = database;
            this.job = job;
        }

        public void execute() {
            // ...
        }
    }
}