bhanwar rathore bhanwar rathore - 4 months ago 70
Java Question

Spring @Autowired field is null?

Why I am getting Spring @Autowired field as null :

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





MainController.java

package com.elastic.controller;

@Component()
@Path("/user")
public class MainController {


@Autowired
private ElasticSearchRepository elasticSearchRepository;

@GET
@Path("/getAllUsers")
@Produces(MediaType.APPLICATION_JSON)
public Response getUsers() throws Exception{

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

while (users.hasNext()) {
userlist.add(users.next());
}

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

}

}





ElasticSearchRepository.java

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

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

}





mvc-dispatcher-servlet.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" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
xsi:schemaLocation="http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">



<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" />


</beans>


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

Answer

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 ElasticSearchRepository.java @ComponentScan(basePackages = { "com.elastic" })

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

Comments