Spring MVC中的Beancreation异常

时间:2018-07-14 05:38:26

标签: java spring hibernate maven spring-mvc

在添加HibernateConfig.java类之前,我的代码成功运行,并且在配置HiberanteConfig.java时出现错误。我已经尝试了很多次来解决此问题,但它反复让我遇到相同的错误。我正在连接的数据库是h2数据库。

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping#0' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'pageController': Unsatisfied dependency expressed through field 'categoryDAO'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'categoryDAO': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionFactory' defined in com.deerwalk.springpasal.config.HibernateConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Factory method 'getSessionFactory' threw exception; nested exception is java.lang.NoSuchMethodError: org.jboss.logging.Logger.debugf(Ljava/lang/String;I)V

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>com.deerwalk</groupId>
    <artifactId>SpringPasal</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>SpringPasal</name>

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

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>


        <!-- Servlet API -->
        <!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- Jstl for jsp page -->
        <!-- http://mvnrepository.com/artifact/javax.servlet/jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>


        <!-- JSP API -->
        <!-- http://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>



        <!-- Spring dependencies -->
        <!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

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

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

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


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

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


        <!-- MySQL JDBC driver -->
        <!-- http://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>


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

         <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.193</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>

dispatcher-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.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.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.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

    <context:component-scan base-package="com.deerwalk.springpasal.* "/>


    <!--
    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="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/views/"
          p:suffix=".jsp" />


    <mvc:annotation-driven/>
   <mvc:resources location="/assets/" mapping="/resources/**" />
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>dispatcher</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
</web-app>

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 com.deerwalk.springpasal.controller;

import com.deerwalk.springpasal.dao.CategoryDAO;
import com.deerwalk.springpasal.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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;


@Controller
@RequestMapping(value="/")
public class PageController {

    @Autowired
    private CategoryDAO categoryDAO;

    @RequestMapping(value={"/","/home"},method = RequestMethod.GET)
    public ModelAndView index(){
        ModelAndView mv=new ModelAndView("page");
        mv.addObject("title","Home");
        mv.addObject("categories",categoryDAO.getAll());
        mv.addObject("userClickHome",true);
        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 Us");
        mv.addObject("userClickContact",true);
        return mv;
    }

   //method to load all product based on 
     @RequestMapping(value="/show/all/products",method = RequestMethod.GET)
    public ModelAndView showAllProducts(){
       ModelAndView mv=new ModelAndView("page");
       mv.addObject("title","All Products");
       mv.addObject("categories",categoryDAO.getAll());
         mv.addObject("userClickAllProducts",true);
        return mv;
    }

     //method to load all product based on 
     @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;
       category= categoryDAO.getById(id);
       mv.addObject("title",category.getName());
          mv.addObject("category",category);
       mv.addObject("categories",categoryDAO.getAll());

         mv.addObject("userClickCategoryProducts",true);

        return mv;
    }
}

HibernateConfig.java

package com.deerwalk.springpasal.config;


import com.deerwalk.springpasal.dao.CategoryDAO;
import com.deerwalk.springpasal.dao.impl.CategoryDAOImpl;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;


@Configuration
@ComponentScan(basePackages = {"com.deerwalk.springpasal.* "})
@EnableTransactionManagement
public class HibernateConfig {

    private final static String DATABASE_URL="jdbc:h2:tcp://localhost/~/shopping";
    private final static String DATABASE_DRIVER="org.h2.Driver";
    private final static String DATABASE_DIALECT="org.hibernate.dialect.H2Dialect";
    private final static String DATABASE_USERNAME="sa";
    private final static String DATABASE_PASSWORD="";


    // dataSource bean will be available
    @Bean("dataSource")
    public DataSource getDataSource() {

        BasicDataSource dataSource = new BasicDataSource();

        // Providing the database connection information
        dataSource.setDriverClassName(DATABASE_DRIVER);
        dataSource.setUrl(DATABASE_URL);
        dataSource.setUsername(DATABASE_USERNAME);
        dataSource.setPassword(DATABASE_PASSWORD);


        return dataSource;

    }

    // sessionFactory bean will be available

    @Bean
    public SessionFactory getSessionFactory(DataSource dataSource) {

    LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource);

        builder.addProperties(getHibernateProperties());
        builder.scanPackages("com.deerwalk.springpasal.entity");

        return builder.buildSessionFactory();

    }



    // All the hibernate properties will be returned in this method 
    private Properties getHibernateProperties() {

        Properties properties = new Properties();


        properties.put("hibernate.dialect", DATABASE_DIALECT);      
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.format_sql", "true");

        //properties.put("hibernate.hbm2ddl.auto", "create");


        return properties;
    }

    // transactionManager bean
    @Bean
    public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
        return transactionManager;
    }

        @Bean(name = "categoryDAO")
    public CategoryDAO getCategoryDAO() {
        return new CategoryDAOImpl();
    }



}

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 com.deerwalk.springpasal.dao.impl;

import com.deerwalk.springpasal.dao.CategoryDAO;
import com.deerwalk.springpasal.entity.Category;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Ashwin
 */
@Repository("categoryDAO")
public class CategoryDAOImpl implements CategoryDAO{

    @Autowired
    private SessionFactory sessionFactory;


    @Override
    public List<Category> getAll() {
       List<Category> categories=new ArrayList<>();
       categories.add(new Category(1,"mobile","mobile","image"));
       categories.add(new Category(2,"TV","TV","image"));
       return categories;
    }

    @Override
    public Category getById(int id) {
       for(Category c:getAll()){
           if(c.getId()==id){
               return c;
           }
       }
       return null;
    }

    @Override
    @Transactional
    public boolean addCategory(Category category) {
        try{
            sessionFactory.getCurrentSession().persist(category);
            return true;
        }catch(Exception ex){

            ex.printStackTrace();
            return false;
        }
    }

}

0 个答案:

没有答案