从任何地方访问 spring 应用程序上下文

Access spring application context from everywhere

让我们假设,我有一个 app-context.xml 可以加载我的 bean 和类似的东西。现在如果我想使用一个bean,我需要做这些步骤:

ApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml");
MailService ms = (MailService) context.getBean("mailService");
// use MailService

我怎样才能跳过这些步骤,因为我不想在每次发送邮件时加载上下文、实例化它、将 bean 转换为我的服务。

另一个问题。为什么加载 XML bean 定义要花那么多时间? 我在 XML 中有 2 个 bean,加载大约需要 2-3-4 分钟。 PC 没问题,在其他应用程序中它可以在几秒钟内加载。

使用@ImportResource从配置文件加载bean。

http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/ImportResource.html