【问题标题】:Why isn't Spring injecting a map into a child Struts 2 Action class but parent's objects are injected?为什么 Spring 不将地图注入子 Struts 2 Action 类,而是注入父对象?
【发布时间】:2011-02-18 22:49:21
【问题描述】:

为了将对象注入到我的 Struts 2 Java 项目中,我在 Spring applicationContext.xml 中有以下配置:

<util:map id="typeToURLMap">
    <entry key="TYPEA" value="./ur1.x" />
    <entry key="TYPEB" value="./url2.x" />
    <entry key="TYPEC" value="./url3.x" />
    <entry key="OTHER" value="./url4.x" />
</util:map>

<bean id="parentAction" class="my.package.ParentAction" scope="prototype">
    <property name="businessDelegate" ref="businessDelegateNotRelevantToThisExample" />
</bean>

<bean id="childAction" class="my.package.ChildAction" scope="prototype" parent="parentAction">
    <property name="typeToURLMap" ref="typeToURLMap"/>
</bean>

由于某种原因,在父 Action 上调用了 setter,但在子 Action 中却没有。 这个配置有什么问题吗?

注意:据我了解,util:map 将默认为 Java 类型的 HashMap。

我的 ParentAction 如下所示:

 public class ParentAction extends MyAppBaseAction {

        private BusinessDelegate businessDelegate;

        //other action code using business delegate

        /**
         *  This IS called.
        */
        public void setBusinessDelegate(BusinessDelegate delegate){
            this.businessDelegate = delegate;
        }
    }

我的 ChildAction 如下所示:

public class ChildAction extends ParentAction{

    private Map<String,String> typeToURLMap;

    //other action code using map

    /**
     *  Never Called! (Why?)
    */
    public void setTypeToURLMap(Map<String,String map){
        this.typeToURLMap = map;
    }
}

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 它会给出“无法设置属性”异常还是只是静默失败?
  • 它默默地失败了。我没有看到任何异常抛出。

标签: java spring struts2 ioc-container


【解决方案1】:

尝试为 applicationContext.xml 文件编写单元测试

public class ApplicationContextTest extends TestCase {

  protected ApplicationContext      ctx;

  protected static final String[]   CONTEXT_LOCATIONS = new String[] {
      "classpath:resources/applicationContext.xml"};

  public void setUp() throws Exception {
    super.setUp();
    ctx = new ClassPathXmlApplicationContext(CONTEXT_LOCATIONS);
  }

  public void test() {
    ChildAction ca = ctx.getBean("childAction", ChildAction.class);
    assertNotNull(ca.getTypeToURLMap());
  }
}

如果测试通过,那么看看struts是如何与spring集成的

【讨论】:

  • 此测试失败,因为注入的 setter 方法从未被触发。我的 struts 配置实例化 ChildAction 并调用正确的方法。真正的问题是注入的地图对象在使用时仍然为空,并抛出 NullPointerException。
  • 你能告诉我你用的是什么版本的spring吗?
  • 哦,是的,对不起,它是 Spring v2.5。我包括以下实用程序库.. springframework.org/schema/util springframework.org/schema/util/spring-util-2.5.xsd
  • Liviu,你建议看看我的 Struts 配置是对的。 struts.xml 使用完全限定的类名而不是 Spring bean 引用,因此它从未被拾取。不过,我仍然有点困惑为什么仍然调用父类的业务代表。我找到了解决方案。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-24
  • 1970-01-01
  • 1970-01-01
  • 2014-08-15
  • 1970-01-01
  • 1970-01-01
  • 2016-05-15
相关资源
最近更新 更多