[英]how to get beans from application context loaded by contextloaderlistener?
I'm new to Spring/Spring Mvc and here's my problem. 我是Spring / Spring Mvc的新手,这是我的问题。 In my webapp, besides the spring-servlet.xml , I have a jdbc.xml which define beans like datasource, dao ... Before using contextloaderlistener , I load my jdbc.xml inside the Controller's constructor like this ApplicationContext context = new ClassPathXmlApplicationContext("jdbcbeans.xml") then get the beans from that. 在我的web应用程序中,除了spring-servlet.xml之外,我还有一个jdbc.xml,它定义了诸如数据源,dao之类的bean。在使用contextloaderlistener之前,我将jdbc.xml加载到了控制器的构造函数中,例如ApplicationContext context = new ClassPathXmlApplicationContext( “ jdbcbeans.xml”),然后从中获取bean。 But since I'm using contextloaderlistener to load the file, how can I get the reference to the context ? 但是,由于我正在使用contextloaderlistener加载文件,因此如何获得对上下文的引用? I was able to set up everything using those @Autowired things but I just want to know is there any way to do that ? 我能够使用这些@Autowired东西来设置一切,但是我只想知道有什么方法可以做到这一点?
You can use WebApplicationContextUtils . 您可以使用WebApplicationContextUtils 。
ApplicationContext context;
context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
You can do the following to get an instance of Application Context in case of a container managed bean use ApplicationContextAware
interface 如果容器管理的bean使用ApplicationContextAware
接口,则可以执行以下操作来获取Application Context的实例
public class MyBean implements ApplicationContextAware {
private static ApplicationContext context;
public void setApplicationContext(ApplicationContext acontext) throws BeansException {
context = context;
}
public static ApplicationContext getApplicationContext() {
return context;
}
}
Or you can write the following 或者您可以编写以下内容
@Autowired
private ApplicationContext Context;
An instance of the Application Context will be autowired. Application Context的实例将被自动装配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.