import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
ApplicationContextAware初始化
通過它Spring容器會自動通過調用ApplicationContextAware接口中的setApplicationContext方法把上下文環境對象注入具體實現類中。
我們在ApplicationContextAware的實現類中,就可以通過這個上下文環境對象得到Spring容器中的Bean。
**/
public class SpringUtil implements ApplicationContextAware, DisposableBean
{
public SpringUtil(){}
/** 屬性注入: Spring框架應用上下文對象 */
private static ApplicationContext applicationContext = null;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
applicationContext = applicationContext;
}
public void destroy()
throws Exception
{
applicationContext = null;
}
public static ApplicationContext getApplicationContext()
{
return applicationContext;
}
public static Object getBean(String name)
throws BeansException
{
return applicationContext.getBean(name);
}
}
/**
applicationContext.xml中配置:
<bean id="springUtil" class="net.eleshop.util.SpringUtil" lazy-init="false" />
web.xml中配置:
<!-- 初始化Spring容器時加載的核心配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/applicationContext*.xml</param-value>
</context-param>
<!-- 配置Spring的核心監聽器: ContextLoaderListener 初始化Spring容器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
**/
SpringUtil
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.