0

I am trying to do a basic test with Spring's @Autowired annotation but I get a NullPointerException.

I checked similar questions but none of them had an answer that worked for me. here is my code :

the OK2 class

@Component
public class OK2 {

    @Autowired
    private Ok test;

    public OK2(){
        this.test.testMethod();
    }
}

the Ok Class

@Component
public class Ok implements Itest{

    public void testMethod(){
        System.out.println("yo");
    }

}

the main class :

public class Test {

    public static void main(String[] args) {
        OK2 o = new OK2();

    }

here is the springtest.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">



   <bean id="Ok" class="infra.Ok"/>
   <bean id="ok2" class="infra.OK2"/>

</beans>

as error I get :

Exception in thread "main" java.lang.NullPointerException
    at infra.OK2.<init>(OK2.java:22)
    at infra.Test.main(Test.java:46)
FrankelStein
  • 907
  • 2
  • 13
  • 30
  • Best approach: Use constructor injection, not field injection. – chrylis -cautiouslyoptimistic- Nov 21 '16 at 00:41
  • Even when I avoid using `new` by using _`ApplicationContext context = new ClassPathXmlApplicationContext("springtest.xml"); OK2 o = (OK2) context.getBean("ok2");`_ I get a NullPointerException – FrankelStein Nov 21 '16 at 00:42
  • Does `springtest.xml` define component-scanning, or does it define the bean directly? Edit question and show it, because it is a critical part of your setup, don't you think? – Andreas Nov 21 '16 at 00:54
  • And now you're using the dependency in the constructor, before Spring has had a chance to autowire fields. This is a major reason field injection is bad. Use a constructor parameter instead, and you don't need Spring at all for your test. – chrylis -cautiouslyoptimistic- Nov 21 '16 at 01:04

0 Answers0