ExternalInvestmentBase

ExternalInvestmentBase

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

   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);
    }
}


主要的问题是


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

最佳答案

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

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

本文介绍了正确的依赖项注入:https://www.javatpoint.com/dependency-injection-in-spring

10-06 10:12