java - Spring 数据 : Injected repository is null

标签 java spring dependency-injection spring-data

不久前,我让 Spring Data 的存储库在 @Controller 中工作。将数据访问向下移动到 @Service 后,它停止工作了。我觉得一切都很好……为什么这个 DI 会失败?

这是我的 Spring 配置:

<?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:data="http://www.springframework.org/schema/data/jpa"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
            http://www.springframework.org/schema/data/jpa
            http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <property name="database" value="POSTGRESQL" />
        <property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" />
    </bean>

    <bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
        <property name="dataSource" ref="dataSource" />
        <property name="jpaDialect" ref="jpaDialect" />
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://localhost:5432/cp" />
        <property name="username" value="cp_user" />
        <property name="password" value="+JMJ+pw0m2d" />
    </bean>

    <data:repositories base-package="com.mydomain.data.repository" />

    <mvc:annotation-driven />

</beans>

我的申请:

@ComponentScan
@EnableAutoConfiguration
@ImportResource("classpath:spring-config.xml")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

我的 Controller :

@Controller
@RequestMapping("/app/user")
@ExposesResourceFor(User.class)
public class UserController {
@RequestMapping(value = "/{userid}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public HttpEntity<UserResource> get(@PathVariable("userid") long id) {
        ProfileService ps = new ProfileService();
        UserResource resource = ps.get(id);
        return new ResponseEntity<UserResource>(resource, HttpStatus.OK);
    }
}

还有我的服务:

@Service
@ExposesResourceFor(User.class)
public class ProfileService {

    @Inject
    private UserRepository users;

    public UserResource get(long id) {
        Long longId = new Long(id);
        User user = users.findOne(longId);  // Line 24

        if (user == null) {
            throw new ResourceNotFoundException();
        }

        UserMapper assembler = new UserMapper();
        UserResource resource = assembler.toResource(user);

        return resource;
    }

    public void update(UserResource resource) {
        UserMapper assembler = new UserMapper();
        User user = assembler.toEntity(resource);
        users.save(user);
    }
}

抛出异常:

java.lang.NullPointerException
com.mydomain.service.ProfileService.get(ProfileService.java:24)
com.mydomain.app.web.UserController.get(UserController.java:74)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:748)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:947)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:878)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:946)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:822)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)

ProfileService:24 在哪里:

User user = users.findOne(longId);

最佳答案

在您的 Controller 中,您使用 new 关键字创建 ProfileService 实例,并且它不受 Spring 管理(Spring 不知道它并且无法注入(inject) UserRepository - 这会导致 NullPointerException)。您必须像将 UserRepository 注入(inject) ProfileService 一样,将 ProfileService 注入(inject)到 UserController 中。例如:

@Controller
@RequestMapping("/app/user")
@ExposesResourceFor(User.class)
public class UserController {

    @Autowired
    private ProfileService profileService;

    @RequestMapping(value = "/{userid}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public HttpEntity<UserResource> get(@PathVariable("userid") long id) {
        UserResource resource = profileService.get(id);
        return new ResponseEntity<UserResource>(resource, HttpStatus.OK);
    }
}

关于java - Spring 数据 : Injected repository is null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21067559/

相关文章:

java - 需要 Spring 版本# - 只有 spring.jar 文件

c# - MediatR 仅使用 ASP.NET DI 在程序集中注册特定处理程序

java - 如何将 JList 元素文本复制到剪贴板

java - 如何在不关闭服务器的情况下清除/删除所有 Weblogic 日志?

java - 使用 sc.nextLine 输入字符串时出错

java - 传递到 Spring JDBC LobHandler 后关闭 Java InputStream?

java - Spring中注销失败如何处理?

android - Roboguice @Inject 服务困惑

c# - 静态方法中的统一

java - 如何从数组中删除空字符串