我写了一个Action,如下/**
 * 
 */
package test;import javax.servlet.ServletContext;import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.swell.CustomerRelationshipManage.action.BaseSupport;/**
 * @author S.Well
 */
@SuppressWarnings("serial")
public class BeanList extends BaseSupport implements ServletContextAware {
private static final Logger logger = Logger.getLogger(BeanList.class
.getName());
public ApplicationContext ctx;
private ApplicationContext childContext;
private String[] beans;
private ServletContext servletContext; public String[] getBeans() {
return beans;
} public void setBeans(String[] beans) {
this.beans = beans;
} public void init() {
this.ctx = WebApplicationContextUtils
.getWebApplicationContext(servletContext);
this.childContext = (ApplicationContext) this.ctx.getBean("managerCTX");
beans = this.childContext.getBeanDefinitionNames();
// beans = this.applicationContext.getBeanDefinitionNames();
// showManagers(this.childContext); logger.debug(this.childContext.getBeanDefinitionCount()); } @Override
public String execute() throws Exception {
// this.childContext.getBeanDefinitionCount();
init();
return super.execute();
} /* (non-Javadoc)
 * @see org.springframework.web.context.ServletContextAware#setServletContext(javax.servlet.ServletContext)
 */
@Override
public void setServletContext(ServletContext servletContext) {
logger.debug("servlet context");
this.servletContext = servletContext; }}
问题是:
把init()中几个步骤分开在另外的函数中。比如,将this.applicationContext在setServletContext中取,然后在 init()中调用this.applicationContext则出错。(this.childContext也是这样。)
代码如下。 public void init() {
this.childContext = (ApplicationContext) this.ctx.getBean("managerCTX");
beans = this.childContext.getBeanDefinitionNames();
// beans = this.applicationContext.getBeanDefinitionNames();
// showManagers(this.childContext); logger.debug(this.childContext.getBeanDefinitionCount()); } @Override
public String execute() throws Exception {
// this.childContext.getBeanDefinitionCount();
init();
return super.execute();
} public void setServletContext(ServletContext servletContext) {
logger.debug("servlet context");
this.servletContext = servletContext;
this.ctx = WebApplicationContextUtils
.getWebApplicationContext(servletContext); }
请高手指点。

解决方案 »

  1.   

    肯定是this.childContext = (ApplicationContext) this.ctx.getBean("managerCTX");
    这一行NullPointerException你要确定一下init方法和setServletContext谁先执行
      

  2.   


    setServletContext 先执行 后execute(),init 在execute 中调用。问题就是,如果把 this.childContext = (ApplicationContext) this.ctx.getBean("managerCTX"); 写到execute中后,再调init()的话,结果是:this.childContext 为null。
    只有把this.childContext = (ApplicationContext) this.ctx.getBean("managerCTX");写入init()才正常。
    我觉得太不可思议了。