1. 新增文件
package com.library.common; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class ApplicationContextHelper implements ApplicationContextAware { private static ApplicationContext appCtx; @Override public void setApplicationContext( ApplicationContext applicationContext ) throws BeansException { appCtx = applicationContext; } public static Object getBean( String beanName ) { return appCtx.getBean( beanName ); } public static <T> T getBean(Class<T> clz) { return (T)appCtx.getBean(clz); } } |
2. 在spring.xml中的最后加入
<bean id=”SpringApplicationContext” class=”com.library.common.ApplicationContextHelper”></bean> |
3. 调用代码
UserService us=ApplicationContextHelper.getBean(UserService.class); |