Raj Kamal
Raj Kamal

Reputation: 11

UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'dao'

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'dao'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'alienDao': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException:

HomeController.java

package com.telusko.springmvc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;


import com.telusko.springmvc.dao.AlienDao;
import com.telusko.springmvc.model.Alien;


@Controller
public class HomeController
{

    @Autowired
     AlienDao dao;

    @ModelAttribute
    public void modelData(Model m) 
    {
    m.addAttribute("name","Aliens");
    }

    @RequestMapping("/")
    public String home()
    {
        return "index";
    }

    @GetMapping("getAliens")
    public String getAliens(Model m)
    {
        m.addAttribute("result", dao.getAliens());
        return "showAliens";

    }

    @RequestMapping("addAlien")
    public String addAlien(@ModelAttribute Alien a)
    {

        return "result";

    }
}

AlienDao.java

 package com.telusko.springmvc.dao;
    import java.util.List;

    import javax.transaction.Transactional;

    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Repository;
    import org.springframework.stereotype.Service;

    import com.telusko.springmvc.model.Alien;

    @Service
    @Repository
    public class AlienDao
    {
        @Autowired
        private SessionFactory sessionFactory;

        @Transactional
    public List<Alien> getAliens()
    {
        Session session = sessionFactory.getCurrentSession();
        List <Alien> aliens = session.createQuery("from Alien",Alien.class).list();

        return aliens;
    }
    }

Alien.java

package com.telusko.springmvc.model;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Alien 
{
    @Id
    private int aid;
    private String aname;

    public int getAid() {
        return aid;
    }
    public void setAid(int aid) {
        this.aid = aid;
    }
    public String getAname() {
        return aname;
    }
    public void setAname(String aname) {
        this.aname = aname;
    }
    @Override
    public String toString() {
        return "Alien [aid=" + aid + ", aname=" + aname + "]";
    }


}

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    Welcome to Telusko

    <form action="addAlien" method="POST">
        Enter your id : <input type="text" name="aid"><br>
        Enter your name : <input type="text" name="aname"><br>
        <input type="submit">
    </form>
</body>
</html>

result.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1" isELIgnored="false"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
        Result is : ${alien}

        Welcome Back ${name}
    </body>
    </html>

showAliens

 <%@ page language="java" contentType="text/html; 
    charset=ISO-8859-1"pageEncoding="ISO-8859-1" isELIgnored="false"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>

        ${result}
    </body>
    </html>

telusko-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>

    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:ctx="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <ctx:component-scan base-package="com.telusko"></ctx:component-scan>
    <ctx:annotation-config></ctx:annotation-config>


    <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/telusko"></property>
    <property name="user" value="root"></property>
    <property name="password" value="12345678"></property>

    <property name="minPoolSize" value="5" />
    <property name="maxPoolSize" value="10" />
    <property name="maxIdleTime" value="30000" />
    </bean>


    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource" />
    <property name="packageToScan" value="com.telusko.springmvc.model" />
    <property name="hibernateProperties">
    <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    <prop key="hibernate.show_sql">true</prop>
    </props>
    </property>  
    </bean>



    <bean id="myTransactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="myTransactionManager" />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    </beans>

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>

  <servlet>
  <servlet-name>telusko</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>

   <servlet-mapping>
   <servlet-name>telusko</servlet-name>
   <url-pattern>/</url-pattern>
   </servlet-mapping>


</web-app>

error Show

HTTP Status 500 – Internal Server Error
Type Exception Report

Message Servlet.init() for servlet [telusko] threw exception

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

javax.servlet.ServletException: Servlet.init() for servlet [telusko] threw exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:688)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
    org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1594)
    org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Unknown Source)
Root Cause

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'dao'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'alienDao': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/telusko-servlet.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'packageToScan' of bean class [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Bean property 'packageToScan' is not writable or has an invalid setter method. Did you mean 'packagesToScan'?
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643)
    org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130)
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422)

Upvotes: 1

Views: 5230

Answers (2)

RIPAN
RIPAN

Reputation: 3886

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'dao'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'alienDao': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/telusko-servlet.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'packageToScan' of bean class [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Bean property 'packageToScan' is not writable or has an invalid setter method. Did you mean 'packagesToScan'?

From the exception itself its pretty clear that, there is no valid setter method for the property "packageToScan". For further debugging, you can open the class session factory class and see if there is any setter method or constructor (if you know how dependency injection works) like setPackageToScan(...).Since there is no setter or constructor like that, spring container fails to inject dependency and the error.As @Codescale already mentioned, modify the property to packagesToScan ( and in the class there is indeed a corresponding setter method, you should no longer to see the error.

Upvotes: 2

CodeScale
CodeScale

Reputation: 3304

Following your stacktrace you have to rename property packageToScan to packagesToScan

Upvotes: 2

Related Questions