Loading the spring context through Applicationcontextawareoriginal September 05, 2013 18:15:44
- Label:
- Spring/
- Applicationcontextaw
The project uses Applicationcontextaware, through which the spring container automatically calls the context object to the Setapplicationcontext method in the Applicationcontextaware interface.
In the Applicationcontextaware implementation class, we can get the beans in the spring container through this context object.
Here's how to use it:
1. Implement the Applicationcontextaware interface:
[Java]View PlainCopy
- Package com.bis.majian.practice.module.spring.util;
- Import org.springframework.beans.BeansException;
- Import Org.springframework.context.ApplicationContext;
- Import Org.springframework.context.ApplicationContextAware;
- Public class Springcontexthelper implements Applicationcontextaware {
- private static ApplicationContext context = null;
- @Override
- public void Setapplicationcontext (ApplicationContext applicationcontext)
- throws Beansexception {
- context = ApplicationContext;
- }
- public static Object Getbean (String name) {
- return Context.getbean (name);
- }
- }
2. Configure this class in the spring configuration file, and the spring container will invoke the Setapplicationcontext method in the object after loading the spring container:
[HTML]View PlainCopy
- <? XML version= "1.0" encoding="UTF-8"?>
- <beans xmlns="Http://www.springframework.org/schema/beans"
- xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http// Www.springframework.org/schema/tx "
- xmlns:context="Http://www.springframework.org/schema/context"
- xsi:schemalocation= "Http://www.springframework.org/schema/beans
- Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- Http://www.springframework.org/schema/tx
- Http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- Http://www.springframework.org/schema/context
- Http://www.springframework.org/schema/context/spring-context-3.0.xsd " default-autowire="byname ">
- <Bean id= "springcontexthelper" class=" Com.bis.majian.practice.module.spring.util.SpringContextHelper "></bean>
- <context:component-scan base-package="com.bis.majian.practice.module.*" />
- </Beans>
3. Configure the listener to load the spring container in Web. XML in a website project:
[HTML]View PlainCopy
- <!--initialize the spring container so that the spring container starts automatically with the launch of the Web App-
- <listener>
- <listener-class>org.springframework.web.context.contextloaderlistener</ Listener-class>
- </Listener>
4. The object in the spring container can be obtained through this springcontexthelper call Getbean () method in the project.
Loading the spring context through Applicationcontextaware