为什么我将Spring @Autowired字段设为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-调度-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>
对于我已保留@component注释,对于存储库,我保留了@Configuration但仍然得到此异常。请帮助解决这个问题。
答案 0 :(得分:2)
根据问题陈述,我能找到两个问题,解决方案如下:
请试试这个
请在ElasticSearchRepository.java类中尝试
@ComponentScan(basePackages = { "com.elastic" })
@Component()
在MainController.java类中使用@Controller
重命名
答案 1 :(得分:0)
这可能是由于你使用MainController
的方式,如果你的主控制器没有被spring上下文初始化和配置,即你使用MainController
关键字创建了new
的实例
其次我在ElasticSearchRepository中没有看到getAllUsers()
方法,只是想知道你的代码是如何编译的?