Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring应用程序中的NoSuchBeanDefinitionException_Java_Spring_Rest_Spring Mvc - Fatal编程技术网

Java Spring应用程序中的NoSuchBeanDefinitionException

Java Spring应用程序中的NoSuchBeanDefinitionException,java,spring,rest,spring-mvc,Java,Spring,Rest,Spring Mvc,我正在创建一个使用REST的应用程序。目前,我的控制器正在使用ServiceMockImplementation实现,但我打算使用数据库,而不是硬编码联系人的值。restful客户端工作正常,在模拟实现使用时在服务器上运行,但当我添加DAO实现时,它崩溃并给我一个NoSuchBeanDefinitionException,即使bean contactDao在我的DAO实现类中被注释为@RepositorycontactDao 这是我的RestfulClientMain: 这是我的联系人控制器:

我正在创建一个使用REST的应用程序。目前,我的控制器正在使用ServiceMockImplementation实现,但我打算使用数据库,而不是硬编码联系人的值。restful客户端工作正常,在模拟实现使用时在服务器上运行,但当我添加DAO实现时,它崩溃并给我一个NoSuchBeanDefinitionException,即使bean contactDao在我的DAO实现类中被注释为@RepositorycontactDao

这是我的RestfulClientMain:

这是我的联系人控制器:

这是我的ContactMock实现。目前,您可以看到它包含硬编码的值,但作为注释,我已经包含了解决此错误后代码实际应该执行的操作。它与DAO交互以从数据库中检索联系人

import java.util.*;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.*;
import com.aucklanduni.spring.webservices.domain.*;

@Service("contactService")
@Component
public class ContactServiceMockImplementation implements ContactService {

    private Contacts _contacts;

    //private ContactDao contactDao;

    public ContactServiceMockImplementation() {
        Contact contact1 = new Contact();
        contact1.setId(1L);
        contact1.setVersion(1);
        contact1.setFirstName("Clint");
        contact1.setLastName("Eastwood");
        contact1.setBirthDate(new Date());

        Contact contact2 = new Contact();
        contact2.setId(1L);
        contact2.setVersion(1);
        contact2.setFirstName("Robert");
        contact2.setLastName("Redford");
        contact2.setBirthDate(new Date());

        Contact contact3 = new Contact();
        contact3.setId(1L);
        contact3.setVersion(1);
        contact3.setFirstName("Michael");
        contact3.setLastName("Caine");
        contact3.setBirthDate(new Date());

        List<Contact> contactList = new ArrayList<Contact>();
        contactList.add(contact1);
        contactList.add(contact2);
        contactList.add(contact3);

        _contacts = new Contacts(contactList);
    }

    @Override
    public List<Contact> findAll() {
        return _contacts.getContacts();
        //return contactDao.findAll();
    }

//  @Override
//  public List<Contact> findByFirstName(String firstName) {
//      List<Contact> results = new ArrayList<Contact>();
//      
//      for(Contact contact : _contacts.getContacts()) {
//          if(contact.getFirstName().equals(firstName)) {
//              results.add(contact);
//          }
//      }
//      return results;
//  }

    @Override
    public Contact findById(Long id) {
        Contact result = null;

        for(Contact contact : _contacts.getContacts()) {
            if(contact.getId() == id) {
                result = contact;
                break;
            }
        }
        return result;
        //return contactDao.findById(id);
    }

    @Override
    public Contact save(Contact contact) {
        return contact;
        //return contactDao.save(contact);
    }

    @Override
    public void delete(Contact contact) {
        // TODO Auto-generated method stub
        //contactDao.delete(contact);
    }

}
启动服务器时,我得到的错误是:

错误:org.springframework.web.servlet.DispatcherServlet-上下文初始化失败 org.springframework.beans.factory.BeanCreationException:创建名为“contactDao”的bean时出错:注入资源依赖项失败;嵌套异常为org.springframework.beans.factory.NoSuchBeanDefinitionException:未找到依赖项类型为[org.hibernate.SessionFactory]的符合条件的bean:应至少有1个符合以下条件的bean 我目前陷入困境,因为我不太确定如何才能将我的ContactService与我的ContactDao链接起来,而不是使用Mock实现方法。任何帮助都将不胜感激。谢谢

以下是我的restful-client-app-context.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" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
                <property name="marshaller" ref="castorMarshaller"/>
                <property name="unmarshaller" ref="castorMarshaller"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <context:component-scan base-package="com.aucklanduni.spring.webservices.restful.controller,
        com.aucklanduni.spring.webservices.service" />

    <bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller">
        <property name="mappingLocation" value="classpath:oxm-mapping.xml"/>
    </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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Root Context: defines shared resources visible to all other web components -->

</beans>
-> org.hibernate.dial.h2方言 3. 50 10 符合事实的 -> 最新日志错误:

[mvcContentNegotiationManager,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,contactController,contactDao,contactService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,castorMarshaller,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@50086ff0
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/contacts/{id}],methods=[DELETE],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public void com.aucklanduni.spring.webservices.restful.controller.ContactController.delete(java.lang.Long)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/contacts/],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public com.aucklanduni.spring.webservices.domain.Contact com.aucklanduni.spring.webservices.restful.controller.ContactController.create(com.aucklanduni.spring.webservices.domain.Contact,javax.servlet.http.HttpServletResponse)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/contacts/{id}],methods=[PUT],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public void com.aucklanduni.spring.webservices.restful.controller.ContactController.update(com.aucklanduni.spring.webservices.domain.Contact,java.lang.Long)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/contacts],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public com.aucklanduni.spring.webservices.domain.Contacts com.aucklanduni.spring.webservices.restful.controller.ContactController.listData(org.springframework.web.context.request.WebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/contacts/{id}],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public com.aucklanduni.spring.webservices.domain.Contact com.aucklanduni.spring.webservices.restful.controller.ContactController.findContactById(java.lang.Long)
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1201f5bc: defining beans [mvcContentNegotiationManager,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,contactController,contactDao,contactService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,castorMarshaller,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@50086ff0
ERROR: org.springframework.web.servlet.DispatcherServlet - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contactDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.aucklanduni.spring.webservices.service.ContactDaoImpl.setSessionFactory(org.hibernate.SessionFactory); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:633)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:602)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:521)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:462)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5210)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5493)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:632)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:670)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1839)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
这是我的web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">

    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/app/root-context.xml</param-value>
    </context-param>

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Configure the Web container to use Spring's DispatcherServlet. DispatcherServlet will 
         forward incoming requests and direct them to application controllers. The Spring container 
         that is used by the The DisplatcherServlet is initialised by the XML file specified by
         the "contextConfiguration" initialisation parameter (i.e. "restful-context.xml"). -->
    <servlet>
        <servlet-name>contactsService</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/app/restful-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Ensure that the servlet executes incoming requests that match the pattern "/*". This means
         that if the application is hosted within a Web container at path "Contact", and if the 
         Web container's domain name is "http://localhost:808", then the servlet will process any
         requests of the form: http://localhost:8080/Contact/, 
         e.g http://localhost:8080/Contact/contacts.   -->
    <servlet-mapping>
        <servlet-name>contactsService</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>
restful-context.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" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
                <property name="marshaller" ref="castorMarshaller"/>
                <property name="unmarshaller" ref="castorMarshaller"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <context:component-scan base-package="com.aucklanduni.spring.webservices.restful.controller,
        com.aucklanduni.spring.webservices.service" />

    <bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller">
        <property name="mappingLocation" value="classpath:oxm-mapping.xml"/>
    </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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Root Context: defines shared resources visible to all other web components -->

</beans>
root-context.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" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
                <property name="marshaller" ref="castorMarshaller"/>
                <property name="unmarshaller" ref="castorMarshaller"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <context:component-scan base-package="com.aucklanduni.spring.webservices.restful.controller,
        com.aucklanduni.spring.webservices.service" />

    <bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller">
        <property name="mappingLocation" value="classpath:oxm-mapping.xml"/>
    </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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Root Context: defines shared resources visible to all other web components -->

</beans>
@资源似乎是按名称布线,而不是按类型布线。您可以改用@Autowired,或者如果您真的想坚持使用符合JSR-250的注释,请使用@Resourcename=springSessionFactory。最后一种选择是将bean重命名为sessionFactory,这将修复所有问题


就在我添加的那一刻,将导入行添加到root-context.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Root Context: defines shared resources visible to all other web components -->
<import resource= "classpath:restful-client-app-context.xml"/> 
</beans>

我们可以看一下restful-client-app-context.xml吗?我的第一个猜测是您没有包含DAO。如果您刚刚添加了xml文件,那么ContactDaoImpl在?com.aucklanduni.spring.webservices.services中是什么包呢?未找到符合依赖项要求的[org.hibernate.SessionFactory]类型的bean:至少需要1个符合此依赖项autowire候选项要求的bean。依赖项注释:springSessionFactory不应该仅仅是sessionFactory吗,因为这是@Resource参数名?不幸的是,对于您的3个建议,我仍然得到相同的错误:该错误明确表示没有[org.hibernate.sessionFactory]类型的合格bean。为什么更改bean名称会带来不同?