您可以使用 ApplicationContextAware。
应用环境感知:
接口将由任何希望通知运行它的应用程序上下文的对象实现。例如,当一个对象需要访问一组协作 Bean 时,实现此接口是有意义的。
有几种方法可以获取对应用程序上下文的引用。您可以实现 ApplicationContextAware,如以下示例所示:
package hello;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
 
@Component
public class ApplicationContextProvider implements ApplicationContextAware {
    private ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    } 
 public ApplicationContext getContext() {
        return applicationContext;
    }
    
}
更新:
当Spring实例化bean时,它会寻找AppplicationContextAware实现,如果找到它们,将调用setApplicationContext()方法。
通过这种方式,Spring设置了当前的应用环境。
来自Spring的代码片段:source code
private void invokeAwareInterfaces(Object bean) {
        .....
        .....
 if (bean instanceof ApplicationContextAware) {                
  ((ApplicationContextAware)bean).setApplicationContext(this.applicationContext);
   }
}
一旦你获得了对应用程序上下文的引用,你就可以使用getBean()获取任何你想要的bean。