jdbcTemplate 为 null 并抛出空指针异常

jdbcTemplate is null and throws null pointer exception

我是 Spring 的新手。我正在尝试使用 Spring web MVC 开发 REST API。我正在尝试使用 JdbcTemplate 从我的数据库中获取一些数据 (MySQL)。但是当我 运行 服务器中的代码时,我得到 500- Internal Server Error 并且堆栈跟踪显示 java.lang.NullPointerException。当我尝试调试代码时,我发现 jdbcTemplate 变量具有空值。我已经尝试了网络中提供的所有解决方案,但仍然出现相同的错误。

这是我的applicationContext.xml文件

    <context:component-scan base-package="com.cinema.repository" />


    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <bean id="userDao" class="com.cinema.repository.UserDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate" />
    </bean>
    <bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <context:property-placeholder location="/WEB-INF/jdbc.properties" />

我的UserDaoImpl.java长相是:

public class UserDaoImpl implements UserDao {
private JdbcTemplate jdbcTemplate;

public JdbcTemplate getJdbcTemplate() {
    return jdbcTemplate;
}
@Autowired
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
}

public User getUser(int userId) {
    String sql ="SELECT * FROM user_tbl WHERE user_id = ?";
    return this.jdbcTemplate.queryForObject(sql,new Object[]{new Integer(userId)}, new UserMapper() );
}

private static final class UserMapper implements RowMapper<User>{
    public User mapRow(ResultSet rs, int rowCount) throws SQLException {
        User u = new User();
        u.setUserId(rs.getInt("user_id"));
        u.setUserName(rs.getString("username"));
        u.setPassword(rs.getString("password"));
        u.setEmailId(rs.getString("email"));
        u.setRole(rs.getString("role"));
        return u;
    }
  }
}

而我的控制器 class 是 UserController.java:

@RestController
@RequestMapping(value="/user")
public class UserController {
    @RequestMapping(method = RequestMethod.GET, value="/{userId}", produces = {MediaType.APPLICATION_JSON_VALUE})
    ResponseEntity<User> getUser(@PathVariable int userId){
        UserDaoImpl user = new UserDaoImpl();
        User u = new User();
        u=user.getUser(userId);
        return new ResponseEntity<User>(u, HttpStatus.OK);
    }
}

我在 运行 应用程序时得到以下堆栈跟踪:

10-Feb-2016 02:50:28.165 SEVERE [tomcat-http--5] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [spring] in context with path [/booking] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.cinema.repository.UserDaoImpl.getUser(UserDaoImpl.java:31)
at com.cinema.web.UserController.getUser(UserController.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:277)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

请告诉我我做错了什么。我已经在这个问题上停留了一个星期了,但仍然无法使我的代码正常工作。提前致谢。

试试这些改变:

@Repository("userDao")
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // Rest of your stuff here.
}

在您的控制器中,您正在创建一个新的 UserDaoImpl :

@RequestMapping(method = RequestMethod.GET, value="/{userId}", produces = {MediaType.APPLICATION_JSON_VALUE})
ResponseEntity<User> getUser(@PathVariable int userId){
    UserDaoImpl user = new UserDaoImpl(); // <-- HERE
    User u = new User();
    u=user.getUser(userId);
    return new ResponseEntity<User>(u, HttpStatus.OK);
}

此 UserDaoImpl 不由 spring 管理,也不由 configured/autowired 管理。 您应该在控制器中注入 xml 中配置的 UserDao 实例:

  @Autowired
  private UserDao userDao;

  @RequestMapping(method = RequestMethod.GET, value="/{userId}", produces = {MediaType.APPLICATION_JSON_VALUE})
ResponseEntity<User> getUser(@PathVariable int userId){
    User u = userDao.getUser(userId);
    return new ResponseEntity<User>(u, HttpStatus.OK);
}