简体   繁体   中英

Object initialization in Java using Dependency Injection

While trying to understand the Dependency Injection principle I came across this example which I couldn't understand

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

The main question is

  1. How does the "this" keyword in the base class work?
  2. How did the ExternalInvestmentBase.supply("tt"); access the object?

The keyword 'this' refers to your current object. The class ExternalInvestmentBase is getting assigned to sImpl as an Object. Here are the Oracle Doc's explaining what it means: https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html I'm not exactly sure why the code uses it that way, to me it seems weird.

Because you have sImpl holding ExternalInvestmentBase as an object the method newExternalInvestmentBase should call the supplymethod on sImpl. This is how ExternalInvestmentBase.supply("tt"); should accesses the object. The method ExternalInvestmentBase.supply can not be used because it is a non static method called from a static context. It wil result in a compilation error.

This article explains correct dependency injection: https://www.javatpoint.com/dependency-injection-in-spring

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM