-1

I got this error even thought I @Inject Message object in MyClass. I just try to learn it now how can I Inject an object.

Please help me, Thanks!

Here are my example.

Main:

public class Main {

    public static void main(String [] arg){
        new MyClass().print();
    }

}

MyClass

import javax.inject.Inject;

public class MyClass {

    @Inject private Message message;

    public void print() {
        System.out.println(message.getMessage());
    }

}

Message

public class Message {

    public String getMessage() {
        return "Hello";
    }

}
Gian
  • 13,735
  • 44
  • 51
Balázs Fodor-Pap
  • 438
  • 1
  • 5
  • 16

1 Answers1

2

You've not got anything that I can see which would interpret or make use of the @Inject annotation. You'll need some kind of DI framework present that will actually do the dependency injection for you. Perhaps consider looking at the minimal examples for something like Guice or Spring?

If you analyze your current program, you're just declaring a field (which is defaulting to null), and never setting it to anything, hence the NPE.

Gian
  • 13,735
  • 44
  • 51