简体   繁体   中英

how to get beans from application context loaded by contextloaderlistener?

I'm new to Spring/Spring Mvc and here's my problem. 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. But since I'm using contextloaderlistener to load the file, how can I get the reference to the context ? I was able to set up everything using those @Autowired things but I just want to know is there any way to do that ?

You can use WebApplicationContextUtils .

ApplicationContext context;
context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

See here for details.

You can do the following to get an instance of Application Context in case of a container managed bean use ApplicationContextAware interface

    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM