waseem khan waseem khan - 10 days ago 5
Java Question

"HTTP Status 500 - Servlet.init() for servlet spring threw exception"

Hi I'm trying a simple Spring MVC CRUD Application using Hibernate and Postgresql . I get Exception which is Below

EXCEPTOIN:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.service.EmployeeService com.controller.EmployeeController.employeeService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dao.EmployeeDao com.serviceImpl.EmployeeServiceImpl.employeeDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.daoImp.EmployeeDaoImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)

org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.service.EmployeeService com.controller.EmployeeController.employeeService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dao.EmployeeDao bean class [com.daoImp.EmployeeDaoImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dao.EmployeeDao com.serviceImpl.EmployeeServiceImpl.employeeDao; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.daoImp.EmployeeDaoImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)

org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dao.EmployeeDao com.serviceImpl.EmployeeServiceImpl.employeeDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDao' defined in file [/Users/mohammad.waseem/Downloads/apache-tomcat-8.5.6/webapps/crud/WEB-INF/classes/com/daoImp/EmployeeDaoImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.daoImp.EmployeeDaoImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)


POM.xml file

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com</groupId>
<artifactId>crud</artifactId>
<packaging>war</packaging>
<version>1.0.0-SNAPSHOT</version>
<name>crud Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<org.springframework.version>3.1.1.RELEASE</org.springframework.version>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc-portlet</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1206-jdbc42</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.1.Final</version>
<classifier>tests</classifier>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.0.1.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.1.0.CR2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
</dependencies>
<build>
<finalName>crud</finalName>
</build>
</project>


Under WEB-INF

web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>


spring-servlet.xml file

<beans xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
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/tx

http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<context:component-scan base-package="com"></context:component-scan>
<tx:annotation-driven transaction-manager="hibernateTransactionManager"></tx:annotation-driven>
<bean id="viewResolver"

class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"

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

<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">

<property name="driverClassName" value="org.postgresql.Driver"></property>

<property name="url" value="jdbc:postgresql://localhost:5433/databasedb"></property>
<property name="username" value="postgres"></property>
<property name="password" value="password"></property>
</bean>

<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">

<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">

<list>
<value>com.model.Employee</value>
</list>

</property>
<property name="hibernateProperties">
<props>

<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
</props>

</property>

</bean>

<bean class="org.springframework.orm.hibernate4.HibernateTransactionManager" id="hibernateTransactionManager">

<property name="sessionFactory" ref="sessionFactory"></property>

</bean>

</beans>


EmployeeBean class under com.bean package

package com.bean;

/**
* Created by mohammad.waseem on 21/11/16.
*/
public class EmployeeBean {
private Integer id;
private String name;
private Integer age;
private Long salary;
private String address;

public EmployeeBean() {
}

public Integer getId() {
return id;
}

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

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public Long getSalary() {
return salary;
}

public void setSalary(Long salary) {
this.salary = salary;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}
}


EmployeeController class under com.controller

package com.controller;

import com.bean.EmployeeBean;
import com.model.Employee;
import com.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* Created by mohammad.waseem on 21/11/16.
*/
@Controller
public class EmployeeController {
@Autowired
private EmployeeService employeeService;

@RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView saveEmployee(@ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
Employee employee = prepareModel(employeeBean);
employeeService.addEmployee(employee);
return new ModelAndView("redirect:/add.html");
}

@RequestMapping(value = "/employees", method = RequestMethod.GET)
public ModelAndView listEmployees() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("employees", prepareListtoBean(employeeService.listEmployeess()));
return new ModelAndView("employeeList", map);
}

@RequestMapping(value = "/add", method = RequestMethod.GET)
public ModelAndView addEmployee(@ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("employees", prepareListtoBean(employeeService.listEmployeess()));
return new ModelAndView("addEmployee", map);
}

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

@RequestMapping(value = "/delete", method = RequestMethod.GET)
public ModelAndView editEmployee(@ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
employeeService.deleteEmployee(prepareModel(employeeBean));
Map<String, Object> map = new HashMap<String, Object>();
map.put("employee", null);
map.put("employees", prepareListtoBean(employeeService.listEmployeess()));
return new ModelAndView("addEmployee", map);
}

@RequestMapping(value = "/edit", method = RequestMethod.GET)
public ModelAndView deleteEmployee(@ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("employee", prepareEmployeeBean(employeeService.getEmployee(employeeBean.getId())));
map.put("Employees", prepareListtoBean(employeeService.listEmployeess()));
return new ModelAndView("addEmployee", map);
}

private Employee prepareModel(EmployeeBean employeeBean) {
Employee employee = new Employee();
employee.setEmpAddress(employeeBean.getAddress());
employee.setEmpAge(employeeBean.getAge());
employee.setEmpName(employeeBean.getName());
employee.setSalary(employeeBean.getSalary());
employee.setEmpId(employeeBean.getId());
employeeBean.setId(null);
return employee;

}

private List<EmployeeBean> prepareListtoBean(List<Employee> employees) {
List<EmployeeBean> employeeBeanList = null;
if (employees != null && !employees.isEmpty()) {
employeeBeanList = new ArrayList<EmployeeBean>();
EmployeeBean employeeBean = null;
for (Employee employee : employees) {
employeeBean = new EmployeeBean();
employeeBean.setName(employee.getEmpName());
employeeBean.setSalary(employee.getSalary());
employeeBean.setAddress(employee.getEmpAddress());
employeeBean.setAge(employee.getEmpAge());
employeeBean.setId(employee.getEmpId());
employeeBeanList.add(employeeBean);
}
}
return employeeBeanList;
}

private EmployeeBean prepareEmployeeBean(Employee employee) {
EmployeeBean employeeBean = new EmployeeBean();
employeeBean.setAddress(employee.getEmpAddress());
employeeBean.setAge(employee.getEmpAge());
employeeBean.setName(employee.getEmpName());
employeeBean.setSalary(employee.getSalary());
employeeBean.setId(employee.getEmpId());
return employeeBean;
}
}


EmployeeDao class under com.dao package

package com.dao;

import com.model.Employee;

import java.util.List;

/**
* Created by mohammad.waseem on 21/11/16.
*/
public interface EmployeeDao{
public void addEmployee(Employee employee);
public List<Employee> listEmployeess();
public Employee getEmployee(int empid);
public void deleteEmployee(Employee employee);
}


EmployeeDaoImpl class under com.daoImp

package com.daoImp;

import com.dao.EmployeeDao;
import com.model.Employee;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
* Created by mohammad.waseem on 21/11/16.
*/
@Repository("employeeDao")
public class EmployeeDaoImpl implements EmployeeDao {
@Autowired
private SessionFactory sessionFactory;

Transaction tx = sessionFactory.getCurrentSession().beginTransaction();


public void addEmployee(Employee employee) {
sessionFactory.getCurrentSession().saveOrUpdate(employee);
}

@SuppressWarnings("unchecked")
public List<Employee> listEmployeess() {
tx.commit();

return (List<Employee>) sessionFactory.getCurrentSession().createCriteria(Employee.class).list();

}

public Employee getEmployee(int empid) {
return (Employee) sessionFactory.getCurrentSession().get(Employee.class, empid);
}

public void deleteEmployee(Employee employee) {
sessionFactory.getCurrentSession().createQuery("Delete from Employee where empid=" + employee.getEmpId()).executeUpdate();
}
}


Employee class under com.model

package com.model;

import javax.persistence.*;
import java.io.Serializable;

/**
* Created by mohammad.waseem on 21/11/16.
*/
@Entity
@Table(name = "EMPLOYEE")
public class Employee implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "empid")
private Integer empId;
@Column(name = "empname")
private String empName;
@Column(name = "empaddress")
private String empAddress;
@Column(name = "salary")
private Long salary;
@Column(name = "empAge")
private Integer empAge;

public Integer getEmpId() {
return empId;
}

public void setEmpId(Integer empId) {
this.empId = empId;
}

public String getEmpName() {
return empName;
}

public void setEmpName(String empName) {
this.empName = empName;
}

public String getEmpAddress() {
return empAddress;
}

public void setEmpAddress(String empAddress) {
this.empAddress = empAddress;
}

public Long getSalary() {
return salary;
}

public void setSalary(Long salary) {
this.salary = salary;
}

public Integer getEmpAge() {
return empAge;
}

public void setEmpAge(Integer empAge) {
this.empAge = empAge;
}
}


EmployeeService interface under com.service package

package com.service;

import com.model.Employee;

import java.util.List;

/**
* Created by mohammad.waseem on 21/11/16.
*/
public interface EmployeeService {
public void addEmployee(Employee employee);
public List<Employee> listEmployeess();
public Employee getEmployee(int empid);
public void deleteEmployee(Employee employee);
}


EmployeeServiceImpl class under com.serviceImpl

package com.serviceImpl;

import com.dao.EmployeeDao;
import com.model.Employee;
import com.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* Created by mohammad.waseem on 21/11/16.
*/
@Service("employeeService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeDao employeeDao;
@Transactional(propagation = Propagation.REQUIRED,readOnly = false)
public void addEmployee(Employee employee) {
employeeDao.addEmployee(employee);
}

public List<Employee> listEmployeess() {
return employeeDao.listEmployeess();
}

public Employee getEmployee(int empid) {
return employeeDao.getEmployee(empid);
}

public void deleteEmployee(Employee employee) {
employeeDao.deleteEmployee(employee);
}
}


I have't much knowledge of MVC so Please help me
thanks in advance

Answer

You are not handling Transaction correctly which is causing the problems, so in your EmployeeDaoImpl, you need to move the Transaction code inside the addEmployee() and deleteEmployee() as shown below:

@Repository("employeeDao")
public class EmployeeDaoImpl implements EmployeeDao {
    @Autowired
    private SessionFactory sessionFactory;

    public void addEmployee(Employee employee) {
        Session session = sessionFactory.getCurrentSession();
        Transaction tx = session.beginTransaction();
        sessionFactory.getCurrentSession().saveOrUpdate(employee);
        tx.commit();
    }

    @SuppressWarnings("unchecked")
    public List<Employee> listEmployeess() {
       Session session = sessionFactory.getCurrentSession();
       Transaction tx = session.beginTransaction();
       Criteria criteria = session.createCriteria(Employee.class);
       List<Employee> list = (List<Employee>)criteria.list();
       tx.commit();
       return list;
    }

    public Employee getEmployee(int empid) {
        return (Employee) sessionFactory.getCurrentSession().get(Employee.class, empid);
    }

    public void deleteEmployee(Employee employee) {
      Session session = sessionFactory.getCurrentSession();
      Transaction tx = session.beginTransaction();
      Query query = session.createQuery("Delete Employee where empid=:empid");
      query.setParameter("empid", employee.getEmpId());
      int result = query.executeUpdate();
      tx.commit();
   }
}

As a best practice, you can make use of @Transactional annotation instead of manually handling the transactions, you can look here

Comments