Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Quick acquisition of bean by ApplicationContextAware

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

The BeanFactory subclass of ApplicationContext has a more powerful function. ApplicationContext can automatically instantiate all bean when the server starts, while BeanFactory only instantiates that bean when getBean () is called. That's why we get an ApplicationContext object. In fact, Spring2-related web applications use ApplicationContext objects to instantiate bean by default, in other words, when the server starts. The Spring container already instantiates an ApplicationContext object, so we'll try to get it in the old code. But how do you get an ApplicationContext object? There are many ways, the most commonly used method is to use ClassPathXmlApplicationContext, FileSystemClassPathXmlApplicationContext, FileSystemXmlApplicationContext and other objects to load the Spring configuration file, which is also possible, but when loading the Spring configuration file, a new ApplicaitonContext object is generated instead of which one the Spring container generates for us, which creates redundancy, so we do not use this way of loading files here. We use ApplicationContextAware to ask the Spring container to pass us its own generated ApplicationContext, and then we set the ApplicationContext to a static variable of the class so that we can get the Application object in the old code at any time. (this paragraph description is transferred from: http://blog.csdn.net/kouwoo/article/details/43405109)

@ Componentpublic class SpringUtils implements ApplicationContextAware {private static ApplicationContext applicationContext; @ Override public void setApplicationContext (ApplicationContext arg0) throws BeansException {applicationContext = arg0;} public static Object getObject (String id) {Object object = null; object = applicationContext.getBean (id); return object;}}

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report