当前位置: 首页 > 知识库问答 >
问题:

autowire字段+注入autowired依赖项是否失败

曾光誉
2023-03-14
ERROR: org.springframework.web.servlet.DispatcherServlet - Context initialization   failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contactController': Injection of autowired dependencies failed
; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: net.viralpatel.spring3.service.ContactService
 net.viralpatel.spring3.controller.ContactController.contactService; nested exception is org.springframework.beans.factory.BeanCreationException: Erro
r creating bean with name 'contactServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.Bean
CreationException: Could not autowire field: private net.viralpatel.spring3.dao.ContactDAO net.viralpatel.spring3.service.ContactServiceImpl.contactDA
O; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contactDAOImpl': Injection of autowired
 dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.Ses
sionFactory net.viralpatel.spring3.dao.ContactDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionExcept
ion: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for
this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProc
essor.java:288)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1120)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
        at.......

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: net.viralpatel.spring3.service.ContactService net.viralp
atel.spring3.controller.ContactController.contactService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'contactServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationExc
eption: Could not autowire field: private net.viralpatel.spring3.dao.ContactDAO net.viralpatel.spring3.service.ContactServiceImpl.contactDAO; nested e
xception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contactDAOImpl': Injection of autowired dependenci
es failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory
 net.viralpatel.spring3.dao.ContactDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No mat
ching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this depend
ency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostP
rocessor.java:514)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProc
essor.java:285)
        ... 30 more
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/applicationContext.xml</param-value>
  </context-param>

  <display-name>SpringMVC3</display-name>

  <servlet>
    <servlet-name>spring3</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/app-config.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>spring3</servlet-name>
    <url-pattern>*.htm</url-pattern>
  </servlet-mapping>
<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 


http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
            http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.2.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
        <!--  Beans for internationalization-->
        <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
            <property name="useCodeAsDefaultMessage" value="true" />
            <property name="basenames">
                 <list>
                    <value>classpath:messages</value>
                 </list>
            </property>
            <property name="cacheSeconds" value="0" />
            <property name="defaultEncoding" value="UTF-8"></property>
        </bean>
        <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
             <property name="defaultLocale" value="en" />
        </bean>

    <!--  Beans or themes support-->
    <bean id="themeSource"
        class="org.springframework.ui.context.support.ResourceBundleThemeSource">
            <property name="basenamePrefix" value="theme-" />
    </bean>

    <bean id="themeResolver"
        class="org.springframework.web.servlet.theme.CookieThemeResolver">
        <property name="defaultThemeName" value="black" />
    </bean> 

    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/*"/>
             <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" >
                 <property name="paramName" value="locale" />
             </bean>
        </mvc:interceptor>
      <mvc:interceptor>
         <mvc:mapping path="/*"/>
             <bean id="themeChangeInterceptor" class="org.springframework.web.servlet.theme.ThemeChangeInterceptor" >
                 <property name="paramName" value="theme" />
             </bean>
        </mvc:interceptor>
    </mvc:interceptors>

    <!-- Scans the classpath of this application for @Components to deploy as beans -->
    <context:component-scan base-package="net.viralpatel.spring3" />

    <!-- Configures the @Controller programming model -->
    <mvc: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/views/"></property>
        <property name="suffix" value=".jsp"></property>        
    </bean>

</beans>
<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">

    <!-- holding properties for database connectivity /-->
    <context:property-placeholder location="classpath:jdbc.properties"/> 

    <!-- enabling annotation driven configuration /-->
    <context:annotation-config/>

     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="${jdbc.driverClassName}"/>
      <property name="url" value="${jdbc.url}"/>
      <property name="username"  value="${jdbc.username}"/>
      <property name="password" value="${jdbc.password}"/>
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>    
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>  </beans>

ContactController.java

package net.viralpatel.spring3.controller;

import java.util.Map;

import net.viralpatel.spring3.form.Contact;
import net.viralpatel.spring3.service.ContactService;

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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
//import org.springframework.web.bind.annotation.SessionAttributes;
//import org.springframework.web.servlet.ModelAndView;

@Controller
public class ContactController {

    @Autowired
    ContactService contactService;

    @RequestMapping("/index")
    public String listContacts(Map<String, Object> map) {
            map.put("contact", new Contact());
            map.put("contactList", contactService.listContact());

            return "contact";
    }   

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addContact(@ModelAttribute("contact")
    Contact contact, BindingResult result) {

        contactService.addContact(contact);

        return "redirect:/index";
    }   

    @RequestMapping("/delete/{contactId}")
    public String deleteContact(@PathVariable("contactId")
    Integer contactId) {

        contactService.removeContact(contactId);

        return "redirect:/index";
    }    

/*
 * JPA ModelAndVIew
    @RequestMapping(value = "/addContact", method = RequestMethod.POST)
    public String addContact(@ModelAttribute("contact")
                            Contact contact, BindingResult result) {

        System.out.println("First Name:" + contact.getFirstname() + 
                    "Last Name:" + contact.getLastname());

        return "redirect:contacts.html";
    }

    @RequestMapping("/contacts")
    public ModelAndView showContacts() {

        return new ModelAndView("contact", "command", new Contact());
    }
*/
}

共有1个答案

云韬
2023-03-14

快速浏览您的代码…

我看不出在哪里/who加载application-context.xml,因此显然您没有得到hibernate SessionFactory、datasource等。

我只能在web.xml上看到您正在通过DispatcherServlet加载app-config.xml

<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
 类似资料:
  • 我做了一些搜索,但我无法找出是什么问题。我知道这个问题来自于ClassNotFoundException,但我无法解决它。 我把我需要的东西都装上了(嗯,我想)。下面是我的代码: DAO类: 服务类别:

  • 在启动springboot应用程序时出现了一些异常。我不知道我错过了什么。 这里是我的代码:这是入口: 这是控制器: 这是pom.xml 这是日志(对格式抱歉): 问题已经修复,我更新了ContextConfig.class,如下所示:` `

  • BeanCreationException:创建名为“Vote Controller”的bean时出错:autowired依赖项的注入失败;嵌套的异常是org.springframework.beans.factory.beanCreationException:不能autowire字段:com.mindtree.service.voteservice com.mindtree.controlle

  • 我有一个集成了spring框架的maven项目,我使用这个项目为移动应用程序构建web服务。当我在AWS ubuntu服务器上部署该项目时,该项目给出了BeanCreationException并且它在Tomcat7上运行失败。当我在本地环境中运行它时,它工作得很好。下面是Tomcat7的错误日志。 TIA

  • 所以我正在尝试学习spring,我已经读了很多教程,并且尝试从闪存驱动器中的一个项目中复制一些代码。 我已经设置了tomcat,它的工作发现,但我仍然有一些问题在这里。问题是,我通常可以毫无问题地从浏览器访问控制器的操作,但当我开始添加注释和ContextLoaderListener时,它一直给我404的状态。我不知道我做了什么,但通过调整一些事情,我的浏览器至少尝试再次到达控制器。但会抛出一个巨