0

I have a bean called InjectionTest and it is annotated with @Component. When i autowire this bean within a controller it works fine. But when i try to use it in another class with @Component annotation, autowire does not work and i get a null pointer exception. Any ideas ?

InjectionTest class

@Component
public class InjectionTest {

    private String word;

    public String getWord() {
        return "test";
     }

     public void setWord(String word) {
       this.word = word;
     }
}

Below is the controller class method which works fine

@Controller
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    AppConfig appConfig;

    @Autowired
    InjectionTest injectionTest;

    @RequestMapping(value = "/api/user/authentication", method = RequestMethod.POST)
    @ResponseBody
    public String authentication(HttpServletResponse res, @RequestParam Map<String, String> allRequestParams,
            HttpServletRequest req) {

        //I dont get an exception in the below line it works fine..
        System.out.println(injectionTest.getWord());
        ....
    }
}

Below is the component which i want to autowire the InjectionTest class and get null pointer exception while creation...

@Component
public class HelloComponent {

    @Autowired
    InjectionTest injectionTest;

    public HelloComponent(){
    //I get null pointer exception in the below line.
        injectionTest.getWord();
    }

}

SEVERE: StandardWrapper.Throwable org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'helloComponent' defined in file [C:\Repo.metadata.plugins\org.eclipse.wst.server.core\tmp3\wtpwebapps\AdaRvmWeb\WEB-INF\classes\tr\com\simroll\ada\rvm\web\entity\HelloComponent.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [tr.com.simroll.ada.rvm.web.entity.HelloComponent]: Constructor threw exception; nested exception is java.lang.NullPointerException

I am really confused. Is there an order or something while creation. If so how can i fix this problem? Thanks..

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
rematnarab
  • 1,277
  • 4
  • 22
  • 42

0 Answers0