Manesh
Manesh

Reputation: 596

Dependency Injection in java

I was trying dependency injection in java using the @Inject annotation and I was following the tutorial in this link. According to the tutorial I created the following.

import javax.inject.Inject;

public class GreetingBean {


@Inject private static HelloBean helloBean;

//  @Inject
//    public GreetingBean(HelloBean helloBean){
//      this.helloBean = helloBean;
//    }

public static void sayGreeting(){
    helloBean.sayHello();
}

public static void main(String[] args) {
    GreetingBean.sayGreeting();
}
} 

The HelloBean class is as follows.

public class HelloBean {

public void sayHello(){
    System.out.println("Hello user");
}
}

On execution I got a null pointer exception which is obvious as helloBean is not initialised. According to what I understood from the tutorial @Inject is supposed to take care of that. I feel that I have to do something more to make this work but I could not find any reference. Can someone help me in this matter.

Upvotes: 0

Views: 482

Answers (1)

Gee2113
Gee2113

Reputation: 268

Take a look here if you want to use CDI with a standard Java application. (This is using the reference CDI implementation, Weld)

Upvotes: 1

Related Questions