简体   繁体   中英

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.

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

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