bhanwar rathore bhanwar rathore - 1 year ago 301
Java Question

Spring @Autowired field is null?

Why I am getting Spring @Autowired field as null :

Exception :
at com.elastic.controller.MainController.getUsers(
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

package com.elastic.controller;

public class MainController {

private ElasticSearchRepository elasticSearchRepository;

public Response getUsers() throws Exception{

List<User> userlist =new ArrayList<User>();
Iterator<User> users = elasticSearchRepository.getAllUsers();

while (users.hasNext()) {

return Response.ok(userlist).build();



package com.elastic.repository;
@EnableElasticsearchRepositories(basePackages = "com.elastic.repository")
public class ElasticSearchRepository {

public Iterator<User> getAllUsers() {
Iterator<User> users = userRepository.findAll().iterator();
return users;



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
xmlns:xsi="" xmlns:mvc=""

<context:annotation-config />

<mvc:annotation-driven />
<context:component-scan base-package="com.elastic" />
<elasticsearch:repositories base-package="com.elastic.repository" />
<elasticsearch:repositories base-package="com.elastic.entity" />


for Controller i have kept @component Annotation and for repository i have kept @Configuration but still getting this exception . Pls help on this .

Answer Source

Based on the problem statement, I am able to find two problems and solution is below:

Please try this

  1. Please try with in the class @ComponentScan(basePackages = { "com.elastic" })

  2. @Component() rename with @Controller in the class

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download