【发布时间】:2016-07-11 10:19:04
【问题描述】:
为什么我将 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-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>
对于控制器,我保留了 @component 注释,对于存储库,我保留了 @Configuration 但仍然出现此异常。请帮忙。
【问题讨论】:
-
这不是 Spring 控制器,而是 Jersey 控制器。使用 Spring MVC 或 Spring-Jersey 集成。
-
怎么做?
-
存储库应该得到
@Repository注解 -
配置公共类 ElasticSearchRepository { 替换为 @Repository 但仍然是相同的问题。
-
并且配置应该在它自己的类中:)