【问题标题】:How to invoke Spring setter method before any other class constructor get invoke?如何在任何其他类构造函数被调用之前调用 Spring setter 方法?
【发布时间】:2012-08-10 08:42:07
【问题描述】:

我有一个动作类,该类将有一个 BOC 对象,该对象将填充 Spring Dependency Injection。下面是示例代码:

public class ActionCls {
  private BOC theBoc = null;

  /*** theBoc getter / setter ***/
}

如果我想在ActionCls 构造函数中调用属于BOC 的成员函数,比如thefunc,如下所示:

public class ActionCls {
   private BOC theBoc = null;

   ActionCls() {
      theBoc.thefunc();
   }
}

将抛出运行时错误,指出theBoc 为空。我确实尝试在这样的弹簧配置中使用init-method

<bean id="theBoc" class="com.huahsin68.BOC" init-method="thefunc"></bean>

无论如何这都无济于事,因为即使首先调用thefunc,但仅在ActionCls 构造函数之后调用theBoc setter。这是一种调用theBoc setter 1st 然后只调用ActionCls 构造函数的方法吗?这样theBoc 不为空,我可以调用thefunc

【问题讨论】:

    标签: java spring dependency-injection


    【解决方案1】:

    您不能期望在调用构造函数之前调用类的 getter 或 setter。你想要达到的目标是不可能的。您可以更好地创建一个参数化构造函数,在其中使用一些参数初始化 theBoc,使用 ActionCls bean 上的 constuctor-arg 参数,然后调用该方法:

    public class ActionCls {
       private BOC theBoc = null;
    
       ActionCls(BOC theBoc) {
          this.theBoc = theBoc
          theBoc.thefunc();
       }
    }
    

    然后你可以像这样定义你的构造函数:

    <bean id="actionCls" class="foo.bar.ActionCls">
            <constructor-arg ref="boc"/>
    </bean>
    

    【讨论】:

      【解决方案2】:

      虽然您不能做您要求的事情(在构造函数中调用属性的方法,而属性是通过 mutator 设置的),但您可以利用 @PostConstruct 让 Spring 调用方法正确组装后在您的 bean 上。

      class ActionCls {
        @Inject
        private BOC boc;
      
        @PostConstruct
        public void postConstruct() {
          boc.func();
        }
      }
      

      http://docs.oracle.com/javaee/5/api/javax/annotation/PostConstruct.html

      【讨论】:

        【解决方案3】:

        除了baba的回答,你可以用init-method(或者@PostConstruct)来解决这个问题,但是应该用在ActionCls而不是BOC上:

        public class ActionCls {
            ...
            public void init() {
               theBoc.thefunc();
            }
        }
        

        .

        <bean ... class="com.huahsin68.ActionCls" init-method="init">...</bean>
        

        我认为这种方法更优雅,因为 init 方法保证在 bean 完全初始化时执行,因此它不依赖于您用于依赖项的注入类型(setter 或构造函数)。

        【讨论】:

        • 没错,这是最好的方法,也是我会使用的方法,但 OP 专门询问如何在构造函数中调用成员函数。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-20
        • 1970-01-01
        • 2013-07-24
        • 2021-08-21
        • 1970-01-01
        相关资源
        最近更新 更多