Tapestry IoC构造函数和注入 [英] Tapestry IoC constructor and injection

查看:94
本文介绍了Tapestry IoC构造函数和注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

public class MyClass {
    @Inject
    private MyAnotherClass myAnotherClass;

    public MyClass() {
        //Perform operations on myAnotherClass.
    }
}

我需要在构造函数中执行一些操作,这些操作需要myAnotherClass的实例.不幸的是myAnotherClass是在构造函数中的代码运行后注入的,这意味着我要在null ...

I need to do some things in constructor which require an instance of myAnotherClass. Unfortunately myAnotherClass is injected after code in constructor is ran, which means I am performing operations on null...

我当然可以直接在构造函数中实例化它的经典方式(MyAnotherClass myAnotherClass = new MyAnotherClass()),但我认为在这种情况下这样做是不正确的.

I could of course instantiate it the classic way (MyAnotherClass myAnotherClass = new MyAnotherClass()) directly in constructor, but I don't think it is the right thing to do in this situation.

您会提出什么解决方案来解决这个问题?

What solutions would you suggest to solve this problem?

推荐答案

最佳选择:

public class MyClass {
  private final MyAnotherClass myAnotherClass;

  public MyClass(MyAnotherClass other) {
    this.myAnotherClass = other;
    // And so forth
  }
}

然后,T5-IoC将使用构造函数注入,因此无需自己新建" MyClass.有关更多信息,请参见定义Tapestry IOC服务.

T5-IoC will then use constructor injection so there's no need to 'new' up MyClass yourself. See Defining Tapestry IOC Services for more info.

或者:

public class MyClass {
  @Inject
  private MyAnotherClass myAnotherClass;

  @PostInjection
  public void setupUsingOther() {
    // Called last, after fields are injected
  }
}

这篇关于Tapestry IoC构造函数和注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆