Home > front end >  Manual dependency injection in Java(without spring boot)
Manual dependency injection in Java(without spring boot)

Time:11-01

I created some classes and an interface like below. Is this regarded as DI? Or It's not because I did new TalkingClockApplication(new TalkingClock());? If it's not, I'd like to know how to make it as DI.(without spring boot)

When I comment out new TalkingClockApplication(new TalkingClock()); and run TalkingClockApplication, it says "com.XXX.TalkingClockApplication.convertTime" is null.


public interface ConvertTime {
    String convertTime(int hours, int minutes);
}

and


public class TalkingClock implements ConvertTime {

    @Override
    public String convertTime(int hours, int minutes) {
        // do something
        return value;
    }
}

and

public class TalkingClockApplication {
    
    public ConvertTime convertTime;
        
    public TalkingClockApplication(ConvertTime convertTime) {
         this.convertTime = convertTime;
    }
    
    public static void main( String[] args ) throws Exception {
        String friendlyText = "";
        TalkingClockApplication aa = new TalkingClockApplication(new TalkingClock());
        int hours = Integer.parseInt(strings[0]);
        int minutes = Integer.parseInt(strings[1]);
        friendlyText = aa.convertTime.convertTime(hours, minutes);
        System.out.println( friendlyText );
    }
}

CodePudding user response:

Spring does not support dependency injection into static fields, so either make your ConvertTime a non-static field or inject it to a non-static field and then assign it to this static one.

CodePudding user response:

When you look at https://en.wikipedia.org/wiki/Dependency_injection and compare it to your solution, then you see, that you implemented most parts (service, client and interface) as it was described there.

But one part is missing: When talking about Dependency Injection, you normaly also have an injector that ist responsible to provide the implementation.

So you could have your implementation of an injector which is responsible to create the instances and inject required elements. (So it might be enough to move that part out of the main method into your Injector and then you simply call the Injector to get your instance of TalkinClockApplication.)

CodePudding user response:

Here in your code : TalkingClockApplication aa = new TalkingClockApplication(new TalkingClock()); you are already doing DI as you are passing your dependency throught a constructor. And also you are using polymorphism that helps you pass any type that implements ConvertTime

Of course you can do DI without spring but what spring provides to you is the ability to automatically provide the implementation you need as you know that you cannot instantiate an interface, here TalkingClock

  • Related