簡體   English   中英

UnsatisfiedDependencyException:創建名為“homeController”的 bean 時出錯:通過字段“dao”表示不滿足的依賴關系

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

org.springframework.beans.factory.UnsatisfiedDependencyException:創建名為“homeController”的bean時出錯:通過字段“dao”表達的依賴關系不滿足; 嵌套異常是 org.springframework.beans.factory.UnsatisfiedDependencyException:創建名稱為“alienDao”的 bean 時出錯:通過字段“sessionFactory”表示的依賴關系不滿足; 嵌套異常是 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;
    }
    }

外星人.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 + "]";
    }


}

索引.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>

結果.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>

顯示外星人

 <%@ 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>

錯誤顯示

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)

在您的堆棧跟蹤之后,您必須將屬性packageToScan重命名為packagesToScan

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'?

從異常本身非常清楚的是,屬性“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容器無法注入依賴和錯誤。正如@Codescale已經提到的,將屬性修改為packagesToScan(並且在class中確實有相應的setter方法,您應該不再看到錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM