-1

i create simple spring project and i need to use annotation @Autowired but when i run project, i get exception NullPointerException.

This is my classes:

Main.java

public class Main {
    @Autowired
    private static InjectClass injectClass;

    public static void setInjectClass(InjectClass injectClass) {
        Main.injectClass = injectClass;
    }
    public static void main(String[] args) {
        injectClass.hello();    //NullPointerException
    }
}

ConfigurationBean

@Configuration
public class ConfigurationBean {
    @Bean
    public InjectClass injectClass(){
        return new InjectClass();
    }
}

InjectClass

public class InjectClass {
    public void hello(){
        System.out.println("Autowired success!");
    }
}
Bohdan Olehovich
  • 575
  • 2
  • 13
  • 26

1 Answers1

0

You need to initiate application contex before using any bean. You can do it by writing following code in starting of your main method. AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( ConfigurationBean.class);

Kuldeep Singh
  • 199
  • 1
  • 11
  • i need use `@Autowired` ! – Bohdan Olehovich Sep 14 '15 at 13:59
  • @BohdanOlehovich which is why you need an **Annotation**ConfigApplicationContext. – zapl Sep 14 '15 at 14:04
  • Because AnnotationConfigApplicationContext is the one who is responsible to initialize all beans defined in configuration class. If you will not create inctance of AnnotationConfigApplicationContext, no bean will be initialized and you will always get null for all beans. – Kuldeep Singh Sep 15 '15 at 04:39