使用工具类获取Spring管理的Bean public static Object getBean(String name) throws BeansException { return applicationContext.getBean(name);} SpringUtil.java /**applicationContext.xml中配置: web.xml中配置: contextConfigLocation
public static Object getBean(String name) throws BeansException { return applicationContext.getBean(name); }SpringUtil.java
/** applicationContext.xml中配置:web.xml中配置: contextConfigLocation classpath*:/applicationContext*.xml **/ import org.springframework.beans.BeansException; import org.springframework.beans.factory.DisposableBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * Spring容器会自动通过调用ApplicationContextAware接口中的setApplicationContext方法把上下文环境对象注入ApplicationContextAware的实现类中。 **/ public class SpringUtil implements ApplicationContextAware, DisposableBean { public SpringUtil() { } /** 属性注入: Spring框架应用上下文对象 */ private static ApplicationContext applicationContext = null; public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.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); } } /** * Demo: @Service("userServiceImpl") * public class UserServiceImpl implements UserService{} * * UserService userService = (UserService)SpringUtil.getBean("userServiceImpl"); **/ org.springframework.web.context.ContextLoaderListener