user2693979
user2693979

Reputation: 2542

Why doesn't field injection work?

I have a Logger class

public class Logger {

   public void log(){
      System.out.println("Logger vagyok!");
   }
}

and a Cow class which injects a Logger.

import javax.inject.Inject;

public class Cow {

   @Inject
   private Logger logger;

   public void speak(){
      logger.log();
   }    
}

But my Main class throws NullPointerException.

public class Main {

    public static void main(String[] args) {
       System.out.println("START");
       Cow cow = new Cow();
       cow.speak(); //THROW NULLPOINTER EXCEPTION HERE!
       System.out.println("END");
    }
}

Why doesn't my field injection work?

Upvotes: 0

Views: 81

Answers (1)

AlexR
AlexR

Reputation: 115328

Field injection does not work itself. You need framework that implements it. For example Spring is a leading injection framework that respects either its own or "standard" injection annotations.

Upvotes: 2

Related Questions