Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring dataSource return null

Tags:

java

mysql

spring

I'm trying to connect MySQL database with Spring. And I also want to use DataSource setter method with @Autowired. Every time I run the code, DataSource always return as null.

Error:

    HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException

Can someone show me whats wrong with my code? Please find below my code.

CustomerController.java

package com.springapp.controller;

import com.springapp.beans.Customer;
import com.springapp.service.CustomerService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;


@Controller
public class CustomerController {

     private CustomerService customerService;

     @RequestMapping(value = "/", method = RequestMethod.GET)
     public ModelAndView index() {
       ModelAndView mv = new ModelAndView("index");
       return mv;
     }


     @RequestMapping(value = "/listCustomers", method = RequestMethod.GET)
     public ModelAndView ListCustomer() {
       ModelAndView mv = new ModelAndView("customers");
       Customer customer = customerService.findCustomerById(1);
       mv.addObject("customer", customer);
       return mv;

     }
}

Customer.java

package com.springapp.beans;

public class Customer {

private int id;
private String firstName;
private String lastName;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

}

CustomerDAO.java

package com.springapp.dao;

import com.springapp.beans.Customer;

 public interface CustomerDAO {

   public Customer findCustomerById(int customerId);

}

CustomerService

 package com.springapp.service;

 import com.springapp.beans.Customer;
 import com.springapp.dao.CustomerDAO;
 import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import javax.sql.DataSource;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Repository;


 @Repository
 public class CustomerService implements CustomerDAO {

 private DataSource dataSource;

 @Autowired
 public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
 }

 @Override
 public Customer findCustomerById(int customerId) {

    String sql = "SELECT * FROM CUSTOMER WHERE CUST_ID = 1";
    Customer customer = new Customer();
    Connection conn = null;
    try {

        conn = dataSource.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            customer.setFirstName(rs.getString("first_name"));
            customer.setLastName(rs.getString("last_name"));
        }
        rs.close();
        ps.close();
        return customer;

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

 }

}

applicationContext.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:p="http://www.springframework.org/schema/p"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/testjavadb" />
        <property name="username" value="root" />
        <property name="password" value="" />
    </bean>

</beans>

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

<context:component-scan base-package="com.springapp" />
<mvc:annotation-driven />

<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
</bean>

Error Log

HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException

type Exception report

message Request processing failed; nested exception is java.lang.NullPointerException

description The server encountered an internal error that prevented it from fulfilling this request.

Exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause

java.lang.NullPointerException
    com.springapp.controller.CustomerController.ListCustomer(CustomerController.java:28)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:497)
    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:749)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.54 logs.
like image 384
Perera1987 Avatar asked Sep 02 '25 16:09

Perera1987


1 Answers

In your CustomerController class, try changing this line:

private CustomerService customerService;

to:

@Autowired
private CustomerService customerService;

or you can auto-wire it via setter or constructor injection, if you like.

like image 93
RichW Avatar answered Sep 04 '25 06:09

RichW