org.springframework.beans.factory.UnsatisfiedDependencyException:对于bean categoryDAO

时间:2017-08-27 10:21:31

标签: java spring hibernate spring-mvc

我的 Category.java 是:

 package shoppingbackend.dto;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity 
public class Category {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    private String description;
    @Column(name = "img_URL")
    private String imageURL;
    @Column(name = "is_active")
    private boolean active = true;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getImageURL() {
        return imageURL;
    }

    public void setImageURL(String imageURL) {
        this.imageURL = imageURL;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    @Override
    public String toString() {
        return "Category [id=" + id + ", name=" + name + ", description=" + description + ", imageURL=" + imageURL
                + ", active=" + active + "]";
    }

}

我的 CategoryDAO.java 是:

package shoppingbackend.dao;
import java.util.List;
import shoppingbackend.dto.Category;
public interface CategoryDAO {
List<Category> list();

 Category getId(int id);
 boolean addCategory(Category category);
 boolean updateCategory(Category category);
 boolean deleteCategory(Category category);
}

我的 CategoryDAOImpl 是:

 package shoppingbackend.daoimpl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import shoppingbackend.dao.CategoryDAO;
import shoppingbackend.dto.Category;

@Repository("categoryDAO")
@Transactional
public class CategoryDAOimpl implements CategoryDAO{

    @Autowired
    private SessionFactory sessionFactory;
    //private static List<Category> categories= new ArrayList<>();

    @Override
    public List<Category> list() {
        String selectActiveCategory="FROM Category WHERE active=:active";
        Query query=sessionFactory.getCurrentSession().createQuery(selectActiveCategory);
        query.setParameter("active", true);

        return query.getResultList();
    }
    @Override
    public Category getId(int id) {

        return sessionFactory.getCurrentSession().get(Category.class,Integer.valueOf(id));

    }
    @Override
    @Transactional
    public boolean addCategory(Category category) {
        // TODO Auto-generated method stub
        try
        {
        sessionFactory.getCurrentSession().persist(category);
        return true;
        }

        catch(Exception e)
        {
            System.out.println("from session catch");
            e.printStackTrace();
            return false;   
        }

    }
    @Override
    public boolean updateCategory(Category category) {
        try
        {
        sessionFactory.getCurrentSession().update(category);
        return true;
        }

        catch(Exception e)
        {
            System.out.println("from session catch");
            e.printStackTrace();
            return false;   
        }

    }
    @Override
    public boolean deleteCategory(Category category) {
        category.setActive(false);
        try
        {
            System.out.println("inside try part");
        sessionFactory.getCurrentSession().update(category);
        return true;
        }

        catch(Exception e)
        {
            System.out.println("from session catch");
            e.printStackTrace();
            return false;   
        }
    }

}

我的 TestCase 是:

package shoppingbackend.test;

import static org.junit.Assert.assertEquals;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import shoppingbackend.dao.CategoryDAO;
import shoppingbackend.dto.Category;

public class CategoryTestCase {


    private static AnnotationConfigApplicationContext context;
    private static CategoryDAO categoryDAO;
    private static Category category;


    @BeforeClass
    public static void init()
    {
        context=new AnnotationConfigApplicationContext();
        context.scan("shoppingbackend");
        context.refresh();
categoryDAO=(CategoryDAO)context.getBean("categoryDAO");

    }
    @Test
    public void testUpdateCategory()
    {
        category=categoryDAO.getId(17);
        category.setName("tubelight");
        System.out.println(category);
        assertEquals("successfully updated a category",true,categoryDAO.updateCategory(category));
    }

}

我的 hibernate config 文件是:

package shoppingbackend.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
//mport org.apache.tomcat.jdbc.pool.DataSource;
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="{shoppingbackend.dto}")
@EnableTransactionManagement
public class HibernateConfig {

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

    @Bean
    public DataSource getDataSource()
    {
        BasicDataSource dataSource =new BasicDataSource();
        dataSource.setDriverClassName(DATABASE_DRIVER);
        dataSource.setUsername(DATABASE_USERNAME);
        dataSource.setUrl(DATABASE_URL);
        dataSource.setPassword(DATABASE_PASSWORD);
        return dataSource;

    }
    //always take care of the hibernate version u are using m using 5 so my Builder will also be of 5
    @Bean
    public SessionFactory getSessionFactory(DataSource dataSource)
    {
        LocalSessionFactoryBuilder builder= new LocalSessionFactoryBuilder(dataSource);
        builder.addProperties(getHibernateProperties());
        builder.scanPackages("shoppingbackend.dto");

    return builder.buildSessionFactory();
    }
    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");

        return properties;

    }



    @Bean
public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory)
{
        HibernateTransactionManager hibernateTransactionManager= new HibernateTransactionManager(sessionFactory);
return  hibernateTransactionManager;
}
}

我的 pom.xml 是:

    <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>onlineshopping</groupId>
  <artifactId>onlineshopping</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <properties>
  <javaee.version>7.0</javaee.version>
  <spring.version>4.3.8.RELEASE</spring.version>
  <hibernate.version>5.2.7.Final</hibernate.version>
  </properties>
  <dependencies>

  <!-- adding backend here -->
<!--   the below idea failed maybe due to the war packaging  -->
 <!-- <dependency>
   <groupId>shoppingbackend</groupId>
  <artifactId>shoppingbackend</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  </dependency> -->
   <!-- adding backend here -->

   <!-- h2 database  -->
  <dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <version>1.4.196</version>
   </dependency>

    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>${javaee.version}</version>
        <scope>provided</scope>

    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
        <exclusions>
        <exclusion>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>${hibernate.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>2.1.1</version>
        <exclusions>
        <exclusion>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.0</version>
    </dependency>

    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.1</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.7.24</version>
    </dependency>
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>2.0.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.0.1.Final</version>
    </dependency>
    <!-- <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency> -->
  </dependencies>
</project>

请帮忙。我很多天都陷入其中,而且我完全不熟悉冬眠了。

整个控制台错误是:

  

在上下文初始化期间遇到异常 - 取消   刷新尝试:   org.springframework.beans.factory.UnsatisfiedDependencyException:   创建名为“categoryDAO”的bean时出错:不满意的依赖项   通过字段'sessionFactory'表示;嵌套异常是   org.springframework.beans.factory.BeanCreationException:错误   创建名为'getSessionFactory'的bean   shoppingbackend.config.HibernateConfig:通过工厂进行Bean实例化   方法失败;嵌套异常是   org.springframework.beans.BeanInstantiationException:失败   实例化[org.hibernate.SessionFactory]:工厂方法   'getSessionFactory'抛出异常;嵌套异常是   org.hibernate.cfg.beanvalidation.IntegrationException:错误   激活Bean Validation集成15.46.11.107   o.s.c.a.AnnotationConfigApplicationContext

2 个答案:

答案 0 :(得分:0)

如果使用hibernate-validator,则必须删除javax.validation依赖项。

欲了解更多信息: Project set up

答案 1 :(得分:0)

取代了这个

<dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.0.1.Final</version>
    </dependency>  

由此:

   <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.2.0.Final</version>
    </dependency> 

并且一切都像以前一样工作....我不知道为什么6.0.2版本之前工作正常....