I am getting below error while creating spring maven rest webservice. When trying to call DAO class with bean name defined in application_config.xml, getting NullPointerException
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/riceAppService] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.ganeshTrading.riceAppService.controller.UserController.getAllUsers(UserController.java:46)
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:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
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:141)
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:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Here, is my code
UserController.java
@RestController
public class UserController {
private JdbcUserDAO jdbcUserDAO;
public JdbcUserDAO getJdbcUserDAO() {
return jdbcUserDAO;
}
public void setJdbcUserDAO(JdbcUserDAO jdbcUserDAO) {
this.jdbcUserDAO = jdbcUserDAO;
}
@RequestMapping("/")
@ResponseBody
public String welcome() {
return "Welcome to RestTemplate Example.";
}
@RequestMapping(value="/users", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public List<User> getAllUsers() {
System.out.println("jdbcUserDAO"+jdbcUserDAO);
List<User> userList = jdbcUserDAO.getAllUsers();
System.out.println(userList);
return userList;
}
}
UserDAO.java
public interface UserDAO {
public List<User> getAllUsers();
}
JdbcUserDAO.java
public class JdbcUserDAO implements UserDAO {
DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public List<User> getAllUsers() {
String sql = "select * from customer";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
System.out.println("getJdbcTemplate() "+jdbcTemplate);
List<User> userList = jdbcTemplate.query(sql, new UserMapper());
return userList;
}
}
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
<context:annotation-config />
<mvc:annotation-driven />
<import resource="classpath:application_config.xml" />
<context:component-scan base-package="com.ganeshTrading.riceAppService" />
</beans>
application_config.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<bean id="jdbcUserDAO" class="com.ganeshTrading.riceAppService.dao.impl.JdbcUserDAO">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/ganeshricetrading"></property>
<property name="username" value="root"></property>
<property name="password" value="sql"></property>
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="w3.org/2001/XMLSchema-instance" xmlns="xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="xmlns.jcp.org/xml/ns/javaee xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
ApplicationConfiguration.java
@ComponentScan(basePackages = {"com.ganeshTrading.riceAppService"})
@Configuration
@EnableWebMvc
public class ApplicationConfiguration {
}
Please advise what is wrong in my code. Thanks in advance.
Although you have defined the jdbcUserDAO
bean, you have not wired it into the UserController
class. This causes a NullPointerException
because the jdbcUserDAO
field is null
, which results in the exception when jdbcUserDAO.getAllUsers()
is called. To solve this, annotate the jdbcUserDAO
setter in the UserController
with @Autowired
, as in:
@RestController
public class UserController {
private JdbcUserDAO jdbcUserDAO;
public JdbcUserDAO getJdbcUserDAO() {
return jdbcUserDAO;
}
@Autowired
public void setJdbcUserDAO(JdbcUserDAO jdbcUserDAO) {
this.jdbcUserDAO = jdbcUserDAO;
}
@RequestMapping("/")
@ResponseBody
public String welcome() {
return "Welcome to RestTemplate Example.";
}
@RequestMapping(value="/users", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public List<User> getAllUsers() {
System.out.println("jdbcUserDAO"+jdbcUserDAO);
List<User> userList = jdbcUserDAO.getAllUsers();
System.out.println(userList);
return userList;
}
}
The @Autowired
annotation tells Spring that a bean that matches the interface of the parameter for the setter (in this case, JdbcUserDAO
) should be injected into the setter, which results in the jdbcUserDAO
field being set to your JdbcUserDAO
bean defined in application_config.xml
.
You could also simplify your UserController
and annotate the field (removing the getter and setter):
@RestController
public class UserController {
@Autowired
private JdbcUserDAO jdbcUserDAO;
@RequestMapping("/")
@ResponseBody
public String welcome() {
return "Welcome to RestTemplate Example.";
}
@RequestMapping(value="/users", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public List<User> getAllUsers() {
System.out.println("jdbcUserDAO"+jdbcUserDAO);
List<User> userList = jdbcUserDAO.getAllUsers();
System.out.println(userList);
return userList;
}
}
For more information, see Guide to Spring @Autowired.
It also looks like your application_config.xml
is not being included in Spring's application context. To include this XML file, change your ApplicationConfiguration
class to resemble the following:
@ComponentScan(basePackages = {"com.ganeshTrading.riceAppService"})
@Configuration
@EnableWebMvc
@ImportResource("classpath:/path/to/application_config.xml")
public class ApplicationConfiguration {
}
Note that classpath:/path/to/application_config.xml
is an example and the actual location of your application_config.xml
file should be used instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With