Jul 06 2008
Access the Spring-ApplicationContext from everywhere in your Application

In this blog i will show you a short hint how you can access your Spring-ApplicationContext from everywhere in your Application.
Imagine you have an application (e.g. a web or swing-application) which you now want to be Spring-enabled. Ok you add the Spring libraries and the Configuration-file and create your Spring-beans. But there are still some old class-files which you can’t use in this way. These files still need access to the Spring-Honeypot where all the goodies exists and you don’t want to redesign your application.
First create the class “ApplicationContextProvider“. This class implements the ApplicationContextAware. A bean which implements the ApplicationContextAware-interface and is deployed into the context, will be called back on creation of the bean, using the interface’s setApplicationContext(…) method, and provided with a reference to the context, which may be stored for later interaction with the context.
ApplicationContextProvider.java
package context;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* This class provides an application-wide access to the
* Spring ApplicationContext! The ApplicationContext is
* injected in a static method of the class "AppContext".
*
* Use AppContext.getApplicationContext() to get access
* to all Spring Beans.
*
* @author Siegfried Bolz
*/
public class ApplicationContextProvider implements ApplicationContextAware {
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
// Wiring the ApplicationContext into a static method
AppContext.setApplicationContext(ctx);
}
} // .EOF
This bean must be initialized in the Spring-Configuration file:
applicationContext.xml
<bean id="contextApplicationContextProvider" class="context.ApplicationContextProvider"></bean>
The key for success is located in the in the method “setApplicationContext(…)“, here we are wiring the injected ApplicationContext into the static method “public static void setApplicationContext(ApplicationContext applicationContext) of the class “AppContext“:
AppContext.java
package context;
import org.springframework.context.ApplicationContext;
/**
* This class provides application-wide access to the Spring ApplicationContext.
* The ApplicationContext is injected by the class "ApplicationContextProvider".
*
* @author Siegfried Bolz
*/
public class AppContext {
private static ApplicationContext ctx;
/**
* Injected from the class "ApplicationContextProvider" which is automatically
* loaded during Spring-Initialization.
*/
public static void setApplicationContext(ApplicationContext applicationContext) {
ctx = applicationContext;
}
/**
* Get access to the Spring ApplicationContext from everywhere in your Application.
*
* @return
*/
public static ApplicationContext getApplicationContext() {
return ctx;
}
} // .EOF
Now you have access from all class-files to the Spring-ApplicationContext in your application, if you call the static method:
Poorfile.java
ApplicationContext ctx = AppContext.getApplicationContext();
Honeypotbean honey = (HoneyPotBean) ctx.getBean("honey");
Do you have any improvements? Please drop a comment below.




Hi Siegfried Bolz
Thank for you article about Spring applicationContex. Today I use your classes it in me application. It work perfect.
See you
Tomas Jurman
Czech Republic
It’s not really necessary to create a separate AppContext class, right? Why not let the ApplicationContextProvider have a static field to hold the application context?
Hello Kal,
yes you can use a static field in the ApplicationContextProvider, my way was to use a separate class.
Very neat program. I was looking for something like this to be injected from a webservice end-point. Works very well. Thanks
Can I ask you one question.
- The application context can be changed every where in the application ?
I have problems in connecting to DB. I can not find any way to change hibernate.default_schema property in my application.
Can you help me ?
Hello Bolz,
Thanks alot for this useful blog. I was trying to get currrent apllication context using many approches,but I could nto succed. Getting applucation context was very import for some complex requirements. Your code solved my issue of application context.
Thanks,
Ratna
Menudo crack !!!!!!!
thanks a lot
Juanma
Spain
Thank you so much!!!
hi
i wanna ask u what do u mean by:
Honeypotbean honey = (HoneyPotBean) ctx.getBean(”honey”);
????
thanks
Hello Ali,
this is just an information how you can get access to all beans stored in the Spring-ApplicationContext (the Honeypot).
Hello Bolz,
i am getting a problem with your code, the method AppContext.getApplicationContext() is returning null, do you have any ideia?
thanks
This solution keeps recreating the beans in the application context over and over again. Obviously a big problem for connection pools. Is there a way to access the application context without creating a new one?
Marcia, the Context will be only once created on the initialization of the application (done by the ApplicationContextAware). If you access the Context, it is always the same and not a new one.
Thanks a lot!!!
It’s working for my application, and it is very usefull.
What other kind of magik can we do with the ApplicationContextAware?? :>
if any have an awnser to my question, please post it.
Thanks a lot too.
Very usefull and nice code.
Wonderful post. I didn’t knew about ApplicationContextAware. Good work.
Thanks Siegfried, A Great post;
A good solution for those who are forced to use someone elses container.
Cheers
Brett
Hi,
I was using,
ctx=new ClassPathXmlApplicationContext(”WEB-INF/applicationContext.xml”);
In this case, it used to create all the beans again. I was able to see that in the log which was as follows…
[code]
NFO [org.springframework.context.support.ClassPathXmlApplicationContext] Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4605c7: display name [org.springframework.context.support.ClassPathXmlApplicationContext@4605c7]; startup date [Thu Aug 06 16:31:47 EDT 2009]; root of context hierarchy
2009-08-06 16:31:47,779 [,] INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] Loading XML bean definitions from class path resource [WEB-INF/applicationContext.xml]
2009-08-06 16:31:48,295 [,] INFO [org.springframework.context.support.ClassPathXmlApplicationContext] Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@4605c7]: org.springframework.beans.factory.support.DefaultListableBeanFactory@179b905
2009-08-06 16:31:48,373 [,] INFO [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer] Loading properties file from class path resource [WEB-INF/classes/trade.properties]
2009-08-06 16:31:48,483 [,] INFO [org.springframework.beans.factory.support.DefaultListableBeanFactory] Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@179b905: defining beans [propertyConfigurer,tradeConfig,transactionManager,contextApplicationContextProvider,fileUploadForm,multiPartSearch,mPContainer,applicationBean,screenReturnPath,BaseListBean,dataTable,voaDataTable,noemDemandTable,oemDemandTable,noemReqLineTable,oemReqLineTable,noemSupplyTable,oemSupplyTable,quoteTable,noemQuoteTable,oemQuoteTable,poHistoryTable,poHistorySngTable,poHistoryAMTable,noemPoHistoryTable,oemPoHistoryTable,noemsoHistoryTable,oemsoHistoryTable,stockTable,searchReqTable,supplyHistTable,supplyNoteTable,demandHistTable,demandNoteTable,myBuyerQuotes,otherBuyerQuotes,custShipToAdd,custBillToAdd,acctSearchTable2,mfrSearchTable2,cnoSearchTable,stocklocationTable,stockNoteTable,arsSearch1,arsSearch2,arsSearch3,poSearch,vendorSearch,soSearchTable,userApprovalLocationsBean,uplLEntryHandler,secRoleHandler,secRoleAdmin,webAppHandler,adminProfileHandler,userLoginHandler,workGroupAdmin,adminWgHandler,SequenceBean,tradeSessionBean,menuNavigation,userBean,tradeAuthenticationController,loginBean,tradeLoginUser,tradeRules,tradeProfiles,tradeProfilesHandler,userAdminBean,userLoginAdminBean,addEditUserLogin,stockItemsVwHandler,multiviewSearch,ddlBean,clearCache,accountVwBean,accountSearchHandler,customerSearchHandler,customerAddressSearchHandler,contactDetailsVwBean,contactDetailsVwHandler,buyerQuoteLinesHandler,otherQuoteLinesHandler,addQuote,buyerQuotesDetails,editQuote,searchBuyerReqReqLinesHandler,viewQuote,viewReqLine,viewBuyerCustomerRequirement,customerReqLinesBean,customerRequirementsBean,upLoadReqLines,uploadSig,custReqLineHistHandler,requirementBuyersBean,requirementBuyersHandler,buyerQuotesBean,quoteLinesHandler,quoteVwBeanHandler,addReqLine,closeRequirement,createCustomerRequirement,customerReqLinesHandler,editCustomerRequirement,editReqLine,searchReqReqLinesHandler,quoteAcceptance,sellerQuoteDetail,arsSupplyHandler,searchArsHandler,arsDemandHandler,stockHandler,controlNoSearchHandler,demandHistVwBean,demandHistVwHandler,demandHistoryDetail,demandNotesBean,demandNotesHandler,demandReqLineHandler,demandSearch,addDemand,editDemand,editSupply,demandSearchHandler,demandSearchVwBean,demandSearchVwHandler,demandBean,demandLBBean,inventoryItemNotesBean,notesBean,mfgSearchHandler,poSearchHandler,poDetail,soDetail,openPoOrdersHandler,hPoDetail,poHistoryBean,poHistoryHandler,poHistorySngHandler,poHistoryAcctMateHandler,searchPOHistory,poHItemHistoryHandler,poReceiptsHandler,itemHistoryVwBean,poNonStockPoolHandler,recievedOrdersHandler,nonStockSearchHandler,openSoOrdersHandler,shippedOrdersHandler,receivedPoOrdersHandler,soHistoryDetail,salesOrderInvoicesHandler,soHistoryHandler,stockItemsDetailBean,stockItemsVwBean,stockItemQuantitiesVwBean,stockLocationList,addSupply,supplyBean,supplyLBBean,supplyHistVwBean,supplyHistVwHandler,supplyHistoryDetail,supplyNotesHandler,supplyNotesBean,supplySearch,supplySearchHandler,vendorSearchHandler,vendorAddressesVwBean,supplySearchVwBean,supplySearchVwHandler,tradeUserBean,soSearchHandler,NextPhase,Trade,ERP,datawarehouse,sqlMapClient,jdbcUtil,jdbcSignatureDAO,pilotUsersVwDAO,soLinesAllDAO,securityRoleDAO,userLoginDAO,userLoginSignaturesDAO,profileLookupValuesDAO,userProfilesDAO,profilesDAO,userRolesDAO,userRolesVwDAO,userTradeGroupsDAO,partVwDAO,mfrDemandSummaryVwDAO,mfrSupplySummaryVwDAO,dwhAccountNotesVwDAO,userLoginTarget,mailService,version,mailSender,email,userLoginService,securityRoleService,acegiFilterChainProxy,httpSessionContextIntegrationFilter,log4jMDCUserFilter,securityRequestFilter,exceptionTranslationFilter,authenticationManager,daoAuthenticationProvider,rememberMeAuthenticationProvider,formAuthenticationProcessingFilter,jdbcLogError,accountAgentDAO,accountDAO,accountsVwDAO,addressDAO,addressTypeDAO,applicationsDAO,businessTypeDAO,businessTypeVwDAO,buyerQuotesDAO,buyerWorkgroupsVwDAO,buyersVwDAO,buyerQuotesVwDAO,commodityTypesVwDAO,commodityManagersVwDAO,contactDAO,contactAddressDAO,contactDetailsVwDAO,contactSearchVwDAO,countriesVwDAO,customerBuyerRequirementsVwDAO,customerRequirementsDAO,customerRequirementLinesDAO,customersVwDAO,customerAddressesVwDAO,erpCustomerContactsVwDAO,requirementLineAvlPartsDAO,customerReqLinesHistVwDAO,customerRequirementsVwDAO,demandVDAO,dateCodesVwDAO,demandHistVwDAO,demandStatusHistDAO,demandBuyersDAO,demandTypesVwDAO,demandNotesDAO,demandSearchVwDAO,erpProcedureDAO,erpPoHeaderDAO,erpPoLinesDAO,salesTermsVwDAO,shipMethodsVwDAO,itemHistoryVwDAO,inventoryItemNotesDAO,jdbcTradeSequenceDAO,jdbcTradeUtilDAO,jdbcControlNoDAO,locationsDAO,lightBoardDAO,manufacturersVwDAO,necxadmCacheObjDAO,xtradeCacheObjDAO,openSoLinesVwDAO,openPoLinesVwDAO,partClassVwDAO,packagingVwDAO,poLineSearchVwDAO,poHeaderDAO,poLineDAO,poSpecialInstructionsVwDAO,specialInstructionsVwDAO,poLineReceiptsVwDAO,phoneDAO,phoneTypeDAO,procedureDAO,productConditionsVwDAO,poHeaderVwDAO,purchaseOrdersAcctmateVwDAO,purchaseOrdersErpVwDAO,purchaseOrdersSngerpVwDAO,purchaseOrderReceiptsVwDAO,quoteStatusesDAO,quoteStatusHistDAO,reqBuyerStatusHistVwDAO,requirementBuyerStatusesDAO,requirementBuyersDAO,requirementStatusesDAO,requirementStatusHistDAO,rohsTypesVwDAO,salespersonsVwDAO,salesOrdersVwDAO,salesOrderInvoicesVwDAO,salesOrderShipmentsVwDAO,erpSoHeadersVwDAO,soHeaderDAO,erpSoLinesVwDAO,shippingLocationsVwDAO,soLineShipmentsVwDAO,stockItemQuantitiesVwDAO,stockItemsVwDAO,supplyVDAO,supplyHistVwDAO,supplyNotesDAO,supplySearchVwDAO,tradeOrganizationsMvDAO,userAccountsDAO,userApprovalLocationDAO,userApprovalLocationVwDAO,userAccountsVwDAO,vendorsVwDAO,vendorAddressesVwDAO,userSearchVwDAO,workGroupUsersVwDAO,workGroupsDAO,workGroupUsersDAO,soHeaderVwDAO,accountService,businessTypeTarget,buyersTarget,buyerQuotesTarget,cacheObjectTarget,contactTarget,commodityManagerTarget,commonTarget,customerService,customerAddressesService,partVwTarget,customerRequirementsTarget,demandTarget,lightBoardTarget,manufacturerTarget,poHistoryService,poService,soService,siService,purchasingTarget,stockItemTarget,userTarget,userAdminTarget,userAccountsServiceTarget,userApprovalLocationsTarget,userRolesTarget,userTradeGroupsTarget,vendorsServiceTarget,dbAdminTarget,salesTarget,arsSupplyDemandTarget,supplyTarget,soLinesAllTarget,validationServiceTarget,workGroupTarget,businessTypeService,buyersService,cacheObjectService,commodityService,contactService,commonService,buyerQuotesService,customerRequirementsService,arsSupplyDemandService,dbAdminService,demandService,lightBoardService,manufacturerService,salesService,purchasingService,supplyService,stockItemsService,userAccountsService,userAdminService,userApprovalLocationsService,userService,userRolesService,userTradeGroupsService,validationService,vendorsService,workGroupService,partVwService,soLinesAllService]; root of factory hierarchy
2009-08-06 16:31:48,483 [,] INFO [org.springframework.transaction.jta.JtaTransactionManager] Using JTA UserTransaction: org.jboss.tm.usertx.client.ServerVMClientUserTransaction@6a21b2
2009-08-06 16:31:48,483 [,] INFO [org.springframework.transaction.jta.JtaTransactionManager] Using JTA TransactionManager: com.arjuna.ats.jbossatx.jta.TransactionManagerDelegate@f3e54b
[/code]
Why is that?
What will happen once when this static context doesn’t created initially and remains null.
Next time, it will not created and beans will not be loaded again…
I think it might create big problem………
Hello,
This works great.
Thanks for the solution.
Hi, how I do get WebApplicationContext, cause the scopes such as session available?
thankx
[...] access the bean with Groovy. Here’s how (it’s more or less a wrapper or extension of this post. The main trick is to implement ApplicationContextAware, which let Spring call the [...]
Was having trouble accessing spring beans from a web filter - had a method that worked fine in WebWork (Using DelegatingFilterProxy), but same model did not seem to be working with Struts2. This method worked fine for accessing spring beans from a filter in struts2.
Hi Siegfried Bolz,
thinks for this solution
I was lost a lot of time to found this solution
Please make sure that the lazy-initialization in the contextApplicationContextProvider bean is set to false.
Thanks - you made my day!!! :-)
Thank you very much.
nice thorough explanation, thanks
Thanks for that, Sigi - YMMD!
I was really lost getting out the spring application context. That helped me out.
See you,
Rene
You can use the WebApplicationContextUtils to get the loaded Spring context in every where you want in the ServletContext, follow this example:
ServletContext servletContext =this.getServletContext();
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
User user = (User)wac.getBean(”user”);
One of the great helpful tips! Clean, concise, and complete. Thank you.
[...] http://blog.jdevelop.eu/2008/07/06/access-the-spring-applicationcontext-from-everywhere-in-your-appl... [...]