得到sessionFactory bean错误

时间:2018-01-20 07:37:32

标签: spring hibernate

例外

  

javax.servlet.ServletException:servlet调度程序的Servlet.init()   引发异常根本原因

     

org.springframework.beans.factory.UnsatisfiedDependencyException:   创建名为'pageController'的bean时出错:不满意的依赖项   通过字段'categoryDAO'表示;嵌套异常是   org.springframework.beans.factory.UnsatisfiedDependencyException:   创建名为'categoryDAOImpl'的bean时出错:不满意   通过字段'sessionFactory'表示的依赖;嵌套异常   是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有   'org.hibernate.SessionFactory'类型的限定bean可用:   预计至少有1个豆有资格成为autowire候选人。   依赖注释:   {@ org.springframework.beans.factory.annotation.Autowired(所需=真)}   根本原因

     

org.springframework.beans.factory.UnsatisfiedDependencyException:   创建名为'categoryDAOImpl'的bean时出错:不满意   通过字段'sessionFactory'表示的依赖;嵌套异常   是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有   'org.hibernate.SessionFactory'类型的限定bean可用:   预计至少有1个豆有资格成为autowire候选人。   依赖注释:   {@ org.springframework.beans.factory.annotation.Autowired(所需=真)}   根本原因

     

org.springframework.beans.factory.NoSuchBeanDefinitionException:没有   'org.hibernate.SessionFactory'类型的限定bean可用:   预计至少有1个豆有资格成为autowire候选人。   依赖注释:   {@ org.springframework.beans.factory.annotation.Autowired(所需=真)}

的applicationContext.xml

<?xml version='1.0' encoding='UTF-8' ?>
    <!-- was: <?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:p="http://www.springframework.org/schema/p"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

        <bean id="propertyConfigurer"
              class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
              p:location="/WEB-INF/jdbc.properties" />

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

        <!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan"  value="org.acem.sha.entity" />
    <property name="hibernateProperties" >
    <props>
        <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
        <prop key="hibernate.show_sql">true</prop>
    </props>
    </property>
    </bean>


    </beans>

分配器一servlet.xml中

<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
        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-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
">
<context:component-scan base-package="org.acem.sha" />
    <mvc:annotation-driven />
    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

    <!--
    Most controllers will use the ControllerClassNameHandlerMapping above, but
    for the index controller we are using ParameterizableViewController, so we must
    define an explicit mapping for it.
    -->
    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="index">indexController</prop>
            </props>
        </property>
    </bean>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/views/"
          p:suffix=".jsp" />

    <!--
    The index controller.
    -->
    <bean name="indexController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="index" />
<!--loading static resources -->
<mvc:resources location="/assets/" mapping="/resources/**" />

</beans>

PageController.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.acem.sha.controller;

import org.acem.sha.dao.CategoryDAO;
import org.acem.sha.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
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.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

/**
 *
 * @author AshwinPC
 */
@Controller
@Transactional
@EnableWebMvc
@RequestMapping(value="/")
public class PageController {

    @Autowired
    private CategoryDAO categoryDAO;

    @RequestMapping(value={"/","/home","/index"},method=RequestMethod.GET)
    public ModelAndView index(){
        ModelAndView mv=new ModelAndView("page");
        mv.addObject("title","Home");
         mv.addObject("userClickHome",true);
         mv.addObject("categories",categoryDAO.list());
        return mv;
    }

    @RequestMapping(value="/about",method=RequestMethod.GET)
     public ModelAndView about(){
        ModelAndView mv=new ModelAndView("page");
        mv.addObject("title","About Us");
         mv.addObject("userClickAbout",true);
        return mv;
    }

      @RequestMapping(value="/contact",method=RequestMethod.GET)
     public ModelAndView contact(){
        ModelAndView mv=new ModelAndView("page");
        mv.addObject("title","contact");
         mv.addObject("userClickContact",true);
        return mv;
    }

     //methods to load all the product and based o category
     @RequestMapping(value="show/all/products",method=RequestMethod.GET)
     public ModelAndView showAllProducts()
     {
         ModelAndView mv=new  ModelAndView("page");
         mv.addObject("categories",categoryDAO.list());

         mv.addObject("title","All Products");
         mv.addObject("userClickAllProducts",true);
         return mv;
     }

     //methods to load all the product and based on category
     @RequestMapping(value="show/category/{id}/products",method=RequestMethod.GET)
     public ModelAndView showCategoryProducts(@PathVariable("id") int id)
     {

         ModelAndView mv=new  ModelAndView("page");
         //categoryDAO to fetch single category
         Category category=null;

         //fetching the single category
         category=categoryDAO.getById(id);

         mv.addObject("title",category.getName());
         mv.addObject("categories",categoryDAO.list());

         //passing the single category
         mv.addObject("category",category);

         mv.addObject("userClickCategoryProducts",true);
         return mv;
     }
}

CategoryDAOImpl.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.acem.sha.dao.impl;

import java.util.ArrayList;
import java.util.List;
import org.acem.sha.dao.CategoryDAO;
import org.acem.sha.entity.Category;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;


/**
 *
 * @author AshwinPC
 */
@Repository
public class CategoryDAOImpl implements CategoryDAO {


   @Autowired
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction trans;


    @Override
    public List<Category> list() {
        session=sessionFactory.openSession();
    List<Category> deptList=session.createQuery("Select c from Category c").list();
    session.close();
    return deptList;
    }

    @Override
    public Category getById(int id) {
       session=sessionFactory.openSession();
        Category dept=(Category)session.get(Category.class,id);
    session.close();
    return dept;
    }

    @Override
    public boolean add(Category category) {
        session=sessionFactory.openSession();
       trans=session.beginTransaction();
        session.save(category);
        trans.commit();
        session.close();
        return true;
    }


    }

的pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.acem.sha</groupId>
    <artifactId>ShoppingApplication</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>ShoppingApplication</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.3.5.RELEASE</spring.version>
        <hibernate.version>4.3.5.Final</hibernate.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.5.2</version>
        </dependency>

        <!--JSTL -->
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
            <scope>provided</scope>
        </dependency>



        <!-- hiberante -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>

        </dependency> 


        <!-- ORM dependency -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>${hibernate.version}</version>
        </dependency>


        <!-- Database connedtion pooling -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.1.1</version>
        </dependency>

       <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>${hibernate.version}</version>
</dependency>

    <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>


        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>7.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

2 个答案:

答案 0 :(得分:1)

我在Maven Hibernate项目中也有同样的例外。 解决方法如下:

HibernateConfiguration.java

package com.okan.config;

import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.mchange.v2.c3p0.ComboPooledDataSource;

@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages="com.okan")
@PropertySource("classpath:db.properties")
public class HibernateConfiguration {

        @Autowired
        private Environment environment;

        @Bean
        public LocalSessionFactoryBean sessionFactory() {
            LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
            sessionFactory.setDataSource(dataSource());
            sessionFactory.setPackagesToScan(new String[] {"com.okan"});
            sessionFactory.setHibernateProperties(hibernateProperties());
            return sessionFactory;
         }

        @Bean
        public DataSource dataSource() {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        try {
        dataSource.setDriverClass(environment.getRequiredProperty("jdbc.driver"));
        } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException();
        }
        dataSource.setJdbcUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUser(environment.getRequiredProperty("jdbc.user"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        dataSource.setInitialPoolSize(Integer.parseInt(environment.getProperty("connection.pool.initialPoolSize")));
        dataSource.setMinPoolSize(Integer.parseInt(environment.getProperty("connection.pool.minPoolSize")));
        dataSource.setMaxPoolSize(Integer.parseInt(environment.getProperty("connection.pool.maxPoolSize")));

        return dataSource;
        }

        private Properties hibernateProperties() {
            Properties properties = new Properties();
            properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
            properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
            properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
            return properties;        
        }

        @Bean
        @Autowired
        public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
           HibernateTransactionManager txManager = new HibernateTransactionManager();
           txManager.setSessionFactory(sessionFactory);
           return txManager;
        }

}

SecurityDemoAppConfig.java

package com.okan.config;
import java.beans.PropertyVetoException;
import java.util.logging.Logger;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.mchange.v2.c3p0.ComboPooledDataSource;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.okan")
@PropertySource("classpath:db.properties")
public class SecurityDemoAppConfig {

    @Autowired
    private Environment env;

    private Logger logger = Logger.getLogger(getClass().getName());



    @Bean
    public DataSource loginDS() {

        ComboPooledDataSource loginDS = new ComboPooledDataSource();

        logger.info("--> Driver bulunuyor");

        try {
            loginDS.setDriverClass(env.getProperty("jdbc.driver"));
            logger.info("--> Driver bulundu");
        } catch (PropertyVetoException e) {
            logger.info("--> Driver bulunamadı");
            throw new RuntimeException("Driver not found");
        }

        logger.info("--> Setting url, user, password");

        loginDS.setJdbcUrl(env.getProperty("jdbc.url"));
        loginDS.setUser(env.getProperty("jdbc.user"));
        loginDS.setPassword(env.getProperty("jdbc.password"));

        logger.info("--> Setting pool properties");

        loginDS.setInitialPoolSize(Integer.parseInt(env.getProperty("connection.pool.initialPoolSize")));
        loginDS.setMinPoolSize(Integer.parseInt(env.getProperty("connection.pool.minPoolSize")));
        loginDS.setMaxPoolSize(Integer.parseInt(env.getProperty("connection.pool.maxPoolSize")));
        loginDS.setMaxIdleTime(Integer.parseInt(env.getProperty("connection.pool.maxIdleTime")));

        return loginDS;
    }

    @Bean
    public ViewResolver viewResolver() {

        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

        viewResolver.setPrefix("/WEB-INF/view/");
        viewResolver.setSuffix(".jsp");

        return viewResolver;
    }

}

答案 1 :(得分:0)

尝试直接在web.xml中指定ApplicationContext.xml的位置,如下所示

<context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/conf/ApplicationContext.xml</param-value>
</context-param>