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
最新推荐文章于 2024-08-11 17:04:09 发布