ApplicationContextAware 得不到Bean
问大家一个很急的问题:
在SSH下 用ApplicationContextAware取不到指定的bean,返回
NullPointerException 异常
有人遇到过吗? 请问是怎么处理的? 在线等待....
代码如下:
一 SpringContextUtil 类
import org.springframework.beans.BeansException;
import
org.springframework.context.ApplicationContext ;
import org.springframework.context.ApplicationContextAware;
/**
* 功能描述:获取spring容器,以访问容器中定义的其他bean
* @author llp
* @version 1.0 2010-11-16
*/
public class SpringContextUtil implements ApplicationContextAware {
// Spring应用上下文环境
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 描述: 传入bean的名称得到bean
* @author llp
* @version 1.0 2010-11-16
* @param name
* @return
* @throws BeansException
*
*/
public static Object getBean(String beanName)throws BeansException {
System.out.println("name===="+beanName);
return applicationContext.getBean(beanName);
}
}
二,获取Bean SocketThread.java
AccessService access = (AccessService)SpringContextUtil.getBean("accessService"); ----------第91行
报错:
java.lang.NullPointerException
at zhhy.web.aims.aimssocket.logic.util.SpringContextUtil.getBean(SpringContextUtil.java:37)
at zhhy.web.aims.aimssocket.socket.SocketThread.run(SocketThread.java:91)
at java.lang.Thread.run(Unknown Source)
------解决方案-------------------- 那你用这一招吧 很管用
ApplicationContext ctx = WebApplicationContextUtils
.getRequiredWebApplicationContext(session.getServletContext());
ServiceImpl serviceImpl = (ServiceImpl) ctx
.getBean("serviceImpl");
配置文件
<bean id="serviceImpl" class="com.ServiceImpl" scope="prototype">
<property name="sqlMapClientTemplate">
<ref bean="sqlMapClientTemplate"/>
</property>
</bean>
------解决方案-------------------- 引用: 谢谢 gudankangti1987
但在我的这些类中是取不到session的 所以不适合!
SpringContextUtil 有注入吗?