您的位置:首页 > 编程语言 > Java开发

SpringContextUtil获取上下文中bean

2018-01-25 16:47 513 查看

一.SpringContextUtil类

public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext; // Spring应用上下文环境

/*
* 实现了ApplicationContextAware 接口,必须实现该方法;
* 通过传递applicationContext参数初始化成员变量applicationContext
*/
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}

public static ApplicationContext getApplicationContext() {
return applicationContext;
}

@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T) applicationContext.getBean(name);
}

public static <T> T getBean(Class<T> clazz) throws BeansException {
return (T) applicationContext.getBean(clazz);
}
}


xml配置

web.xml

<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:SpringServlet.xml</param-value>
</init-param>
<!--随tomcat启动一起加载 -->
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>


SpringServlet.xml

<!-- 可通过SpringContextUtil获取Spring容器中的任何bean -->
<bean id="springContextUtil" class="com.kylin.aep.utils.SpringContextUtil"
scope="singleton" />


这样,在根据SpringServlet.xml初始化上下文时,会自动调用setApplicationContext()方法去获取ApplicationContext。

使用

PermeateService permeateServiceImpl = SpringContextUtil.getBean(PermeateServiceImpl.class);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring