关于 java:org.springframework.beans.factory.UnsatisfiedDependencyException: Error created bean with name \\’bookDaoImpl\\’

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookDaoImpl'

大家!

Java Eclipse Maven SpringMVC Hibernate Tomcat

我手动创建项目 https://www.boraji.com/index.php/spring-mvc-4-hibernate-5-restful-crud-operations-example 完全相同,它不能在我的 Eclipse 中工作(((因为:

1
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookDaoImpl': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionFactory' defined in com.example.spring.config.AppConfig: Invocation of init method failed;

任何帮助,我必须为我的项目工作解决什么问题?现在 CRUD 方法不起作用,但服务器 Tomcat 正在运行...

我的项目在 https://github.com/OlegSandro/library-service 或者你可以在下面看到我的代码:

pom.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<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.example.spring</groupId>
  library-service</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <failOnMissingWebXml>false</failOnMissingWebXml>
    <hibernate.version>5.2.8.Final</hibernate.version>
  </properties>

  <dependencies>
    <!-- Servlet API -->
    <dependency>
        <groupId>javax.servlet</groupId>
        javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    <!-- Spring MVC -->
    <dependency>
        <groupId>org.springframework</groupId>
        spring-webmvc</artifactId>
        <version>4.3.10.RELEASE</version>
    </dependency>
    <!-- Spring ORM -->
    <dependency>
        <groupId>org.springframework</groupId>
        spring-orm</artifactId>
        <version>4.3.10.RELEASE</version>
    </dependency>
    <!-- Hibernate ORM -->
    <dependency>
        <groupId>org.hibernate</groupId>
        hibernate-core</artifactId>
        <version>${hibernate.version}</version>
    </dependency>
    <!-- Hibernate-c3p0 Integration -->
    <dependency>
        <groupId>org.hibernate</groupId>
        hibernate-c3p0</artifactId>
        <version>${hibernate.version}</version>
    </dependency>
    <!-- c3p0 -->
    <dependency>
        <groupId>com.mchange</groupId>
        c3p0</artifactId>
        <version>0.9.5.2</version>
    </dependency>
    <!-- MySQL Connector -->
    <dependency>
        <groupId>mysql</groupId>
        mysql-connector-java</artifactId>
        <version>6.0.5</version>
    </dependency>
    <!-- Jackson API for JSON -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        jackson-databind</artifactId>
        <version>2.8.7</version>
    </dependency>

  </dependencies>

  <build>
    <sourceDirectory>src/main/java</sourceDirectory>
    <plugins>
        <plugin>
            maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>

        <!-- Embedded Apache Tomcat required for testing war -->
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <path>/</path>
            </configuration>
        </plugin>
    </plugins>
  </build>
</project>

model.Book.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
    package com.example.spring.model;

    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;

    @Entity(name ="Book")
    public class Book {

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        private String title;
        private String author;

        public Book() {
        }

        public Long getId() {
            return id;
        }

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

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getAuthor() {
            return author;
        }

        public void setAuthor(String author) {
            this.author = author;
        }
    }

controller.BookController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.example.spring.service;

    import java.util.List;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;

    import com.example.spring.dao.BookDao;
    import com.example.spring.model.Book;

    @Service
    @Transactional(readOnly = true)
    public class BookServiceImpl implements BookService {

        @Autowired
        private BookDao bookDao;

        @Transactional
        public long save(Book book) {
            return bookDao.save(book);
        }

        public Book get(long id) {
            return bookDao.get(id);
        }

        @Transactional
        public void update(long id, Book book) {
            bookDao.update(id, book);

        }

        @Transactional
        public void delete(long id) {
            bookDao.delete(id);
        }

        public List<Book> list() {
            return bookDao.list();
        }

    }

service.BookServiceImpl.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.example.spring.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.spring.dao.BookDao;
import com.example.spring.model.Book;

@Service
@Transactional(readOnly = true)
public class BookServiceImpl implements BookService {

    @Autowired
    private BookDao bookDao;

    @Transactional
    public long save(Book book) {
        return bookDao.save(book);
    }

    public Book get(long id) {
        return bookDao.get(id);
    }

    @Transactional
    public void update(long id, Book book) {
        bookDao.update(id, book);

    }

    @Transactional
    public void delete(long id) {
        bookDao.delete(id);
    }

    public List<Book> list() {
        return bookDao.list();
    }

}

dao.BookDaoImpl.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.example.spring.dao;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

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

import com.example.spring.model.Book;

@Repository
public class BookDaoImpl implements BookDao {

    @Autowired
    private SessionFactory sessionFactory;

    public long save(Book book) {
        sessionFactory.getCurrentSession().save(book);
        return book.getId();
    }

    public Book get(long id) {
        return sessionFactory.getCurrentSession().get(Book.class, id);
    }

    public void update(long id, Book book1) {
        Session session = sessionFactory.getCurrentSession();
        Book book2 = session.byId(Book.class).load(id);
        book2.setTitle(book1.getTitle());
        book2.setAuthor(book1.getAuthor());
        session.flush();
    }

    public void delete(long id) {
        Session session = sessionFactory.getCurrentSession();
        Book book = session.byId(Book.class).load(id);
        session.delete(book);
    }

    public List<Book> list() {
        Session session = sessionFactory.getCurrentSession();
        CriteriaBuilder cb = session.getCriteriaBuilder();
        CriteriaQuery<Book> cq = cb.createQuery(Book.class);
        Root<Book> root = cq.from(Book.class);
        cq.select(root);
        Query<Book> query = session.createQuery(cq);
        return query.getResultList();
    }

}

config.WebConfig.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.example.spring.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.example.spring.controller" })
public class WebConfig extends WebMvcConfigurerAdapter {

}

config.AppConfig.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.example.spring.config;

import java.util.Properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
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 static org.hibernate.cfg.Environment.*;

@Configuration
@PropertySource("classpath:db.properties")
@EnableTransactionManagement
@ComponentScans(value = { @ComponentScan("com.example.spring.dao"),
        @ComponentScan("com.example.spring.service")})
public class AppConfig {

    @Autowired
    private Environment env;

    @Bean
    public LocalSessionFactoryBean getSessionFactory() {
        LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();

        Properties props = new Properties();
        // Setting JDBC properties
        props.put(DRIVER, env.getProperty("mysql.driver"));
        props.put(URL, env.getProperty("mysql.url"));
        props.put(USER, env.getProperty("mysql.user"));
        props.put(PASS, env.getProperty("mysql.password"));

        // Setting Hibernate properties
        props.put(SHOW_SQL, env.getProperty("hibernate.show_sql"));
        props.put(HBM2DDL_AUTO, env.getProperty("hibernate.hbm2ddl.auto"));

        // Setting C3P0 properties
        props.put(C3P0_MIN_SIZE, env.getProperty("hibernate.c3p0.min_size"));
        props.put(C3P0_MAX_SIZE, env.getProperty("hibernate.c3p0.max_size"));
        props.put(C3P0_ACQUIRE_INCREMENT, env.getProperty("hibernate.c3p0.acquire_increment"));
        props.put(C3P0_TIMEOUT, env.getProperty("hibernate.c3p0.timeout"));
        props.put(C3P0_MAX_STATEMENTS, env.getProperty("hibernate.c3p0.max_statements"));

        factoryBean.setHibernateProperties(props);
        factoryBean.setPackagesToScan("com.example.spring.model");

        return factoryBean;
    }

    @Bean
    public HibernateTransactionManager getTransactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(getSessionFactory().getObject());
        return transactionManager;
    }
}

config.MyWebAppInitializer.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.example.spring.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class< ? >[] getRootConfigClasses() {
        return new Class[] { AppConfig.class };
    }

    @Override
    protected Class< ? >[] getServletConfigClasses() {
        return new Class[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] {"/" };
    }

}

resources.db.properties

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# MySQL properties
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/library
mysql.user=root
mysql.password=****

# Hibernate properties
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update

#C3P0 properties
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=1
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=150


能够在本地重现此问题并修复它。

尝试将 mysql-connector-java 的 artifact 版本更新到最新版本

1
2
3
4
5
<dependency>
    <groupId>mysql</groupId>
    mysql-connector-java</artifactId>
    <version>8.0.16</version>
</dependency>

如果您使用的是最新/更新的 MySQL 版本(除了帖子中提到的版本),这是必需的

相关问题:如何解决无法加载身份验证插件caching_sha2_password 问题

如果没有帮助,请提供完整的堆栈跟踪,否则接受解决方案。

顺便说一句,建议使用spring boot,它更简单,更高级。