0

在尝试理解依赖注入原理时,我遇到了这个我无法理解的示例

   abstract class ExternalInvestmentBase {
    private static ExternalInvestmentBase sImpl;

    protected ExternalInvestmentBase() {
        sImpl = this;
    }

    public static String supply(String request) throws Exception {
        return sImpl.supplyImpl(request);
    }

    abstract String supplyImpl(String request)
            throws Exception;
}


class InvestmentUtil extends ExternalInvestmentBase {

    public static void init() {
        new InvestmentUtil();
    }


    @Override
    public String supplyImpl(String request) throws Exception {
        return "This is possible";
    }
}

public class IExternalInvestment {
    public static void main(String[] args) throws Exception {
        InvestmentUtil.init();

        String rv = ExternalInvestmentBase.supply("tt");
        System.out.println(rv);
    }
}

主要问题是

  1. 基类中的“this”关键字是如何工作的?
  2. 对象是如何ExternalInvestmentBase.supply("tt");访问的?
4

1 回答 1

1

关键字“this”指的是您当前的对象。ExternalInvestmentBase 类作为对象分配给 sImpl。以下是 Oracle Doc 解释它的含义:https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html 我不完全确定代码为什么这样使用它,对我来说这似乎很奇怪.

因为您有 sImpl 将 ExternalInvestmentBase 作为对象,所以 newExternalInvestmentBase 方法应该调用 sImpl 上的 supplymethod。这就是 ExternalInvestmentBase.supply("tt"); 应该访问对象。无法使用方法 ExternalInvestmentBase.supply,因为它是从静态上下文调用的非静态方法。这将导致编译错误。

这篇文章解释了正确的依赖注入:https ://www.javatpoint.com/dependency-injection-in-spring

于 2019-11-22T07:40:28.273 回答