0

Im trying to learn Spring but Im having a little trouble using the @Autowired annotation. When I try to run the example below im getting an nullpoint error on classA.hello();line and im not sure why. Any hwlp would be appreciated.

ClassATest

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;

@ContextConfiguration(classes = {ContextConfigurationClass.class})
public class ClassATest {

    @Autowired
    ClassA classA;

    @Test
    public void test(){
        classA.hello();
    }
    }    

ClassA

package com;

import org.springframework.stereotype.Service;

@Service
public class ClassA {

    public void hello(){
        System.out.println("HELLO");
    }
}

Context Configuration

package com;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan({"com"
})
public class ContextConfigurationClass {

}
KahunaDub
  • 89
  • 1
  • 8
  • 1
    You're missing an annotation or a configuration, to make the Autowired working, look [here](https://stackoverflow.com/questions/19414734/understanding-spring-autowired-usage) for more info (or one of the related question) – WoAiNii Jun 05 '20 at 19:16

1 Answers1

0

The NullPointerException occurs because the test doesn't create a Spring context and therefore doesn't inject ClassA.

To solve this, add @RunWith(SpringRunner.class) to ClassATest.

Roland Weisleder
  • 9,668
  • 7
  • 37
  • 59