NoSuchBeanDefinitionException How to initialise SessionFactory bean?

后端 未结 3 1610
面向向阳花
面向向阳花 2021-01-13 22:15

I have a question. I tried to run my web application using Spring and Hibernate/ I have a strange error. NoSuchBeanDefinitionException. Stacktrace is:

Caused         


        
3条回答
  •  悲哀的现实
    2021-01-13 22:39

    I would start with cleaning your configuration

    This

    
    

    Includes all this

    
    
    
    
    
    
    
    

    You are using component scanning so no need to explicitly define all the beans (it would make component scanning pretty useless if that was still needed).

    Next these 2 beans

    
    
    
    

    Are already implied by

    Basically leaves you with this

    
    
    
    
    
    
    
    
        
        
        
    
    
    
        
        
        
        
    
    
    
        
        
            
                com.example.entity.User
                com.example.entity.Role
            
        
        
            
                hibernate.dialect=org.hibernate.dialect.H2Dialect
                hibernate.show_sql=true
            
      
    
    
    
        
    
    

    Not that it will solve your problem because the error is not due to the fact that the configuration is incomplete, but the configuration is in the wrong place. The datasource, sessionFactory, transactionManager and must be moved to the applicationContext.xml. Nex to that your applicationContext.xml should also include a component-scan which scans for everything but controllers.

        
        
    
    

    Change the in your servlet-context.xml to

    
        
    
    

    This to prevent duplicate instantiation of your @Service and @Repository beans. Which is what is happening now (both your ContextLoaderListener and DispatcherServlet are loading and creating the same beans, which would lead you to other nice exceptions and next to that duplication of memory as you have 2 instances of each bean in memory).

提交回复
热议问题