我有以下类(class):
@SpringBootApplication
@ImportResource("classpath:path-to-application-context.xml")
public class SocketMain extends SpringBootServletInitializer {
public static void main(String [] args) {
// ...
}
}
我想访问我的 main
函数中的应用程序上下文,以便我可以获取我定义的 bean 之一。我无法 Autowiring 它,因为您无法 Autowiring 静态变量。有没有办法获取对使用 @ImportResource
注释加载的 applicationContext 的引用?
我的后备方法是在 main
中加载 applicationContext,如下所示:
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("path-to-application-context.xml");`
但我不想加载两次。
提前致谢!
最佳答案
这是在 Spring 中检索应用程序上下文并检索 bean 的方法。这应该放在你的主函数中
ApplicationContext ctx = SpringApplication.run(SocketMain.class, args);
SomeClass sc = ctx.getBean(SomeClass.class);
sc.testRun();
您还应该能够使用@Autowired
检索上下文。
@Autowired
private ApplicationContext context;
关于java - 使用 @ImportResource 注释获取对 ApplicationContext 的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44072486/