jdbcTemplate为null并抛出空指针异常

时间:2016-02-09 21:26:50

标签: java mysql rest spring-mvc spring-web

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

这是我的 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;
    }
  }
}

我的控制器类是 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)

请告诉我这里我做错了什么。我已经坚持这个问题一个星期了,仍然无法使我的代码工作。提前致谢。

2 个答案:

答案 0 :(得分:4)

在您的控制器中,您正在创建一个新的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管理,未配置/自动装配。 您应该在控制器中注入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);
}

答案 1 :(得分:0)

尝试以下更改:

func presentWinningAlert(title: String){
moveCounter = 0
let alert = UIAlertController(title: title, message: "byr", preferredStyle: UIAlertControllerStyle.Alert)