@Davidaa_WoW

Почему возникает org.springframework.beans.factory.UnsatisfiedDependencyException, при попытке подключения к PostgreSQL?

Пытаюсь подключить проект к БД, делаю всё по примеру: https://spring.io/guides/gs/accessing-data-mysql/
Есть значит основная сущность - Author:
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import javax.persistence.*;

@Entity
@Getter
@Setter
@ToString
public class Author {
    @Id
    @GeneratedValue( strategy =
            GenerationType.AUTO)
    private long id;

    private String firstName;

    private String lastName;

    private String middleName;

    private String birthDate;

    public Author() {
    }

    public Author(String firstName, String lastName, String middleName, String birthDate) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.middleName = middleName;
        this.birthDate = birthDate;
    }

}


Есть его контроллер:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashSet;

@RestController
public class AuthorController {
    @Autowired
    private AuthorRepo authorRepo;
    private static Logger LOG = LoggerFactory
            .getLogger(FifteenthApplication.class);
    @GetMapping("/author")
    public String authorGet(@RequestParam(value = "firstName", defaultValue = "null") String name, @RequestParam(value = "all", defaultValue = "false") String all){
        String list = "";
        try {
            if(all.equals("true")){
                Iterable<Author> authors = authorRepo.findAll();
                for(Object k : authors){
                    list += (k.toString());
                }
                return list;
            }
            return "null";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @PostMapping("/author")
    public String authorPost(@RequestParam(value = "firstName", defaultValue = "null") String firstName, @RequestParam(value = "lastName", defaultValue = "null") String lastName, @RequestParam(value = "middleName", defaultValue = "null") String middleName, @RequestParam(value = "birthDate", defaultValue = "null") String birthDate){
        Author author = new Author(firstName, lastName, middleName, birthDate);
        authorRepo.save(author);
        return "Success";
    }


Есть пустой интерфейс репозиторий:
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface AuthorRepo extends CrudRepository <Author, Long> {
}


Есть собственно сам Main:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FifteenthApplication {

	public static void main(String[] args) {
		SpringApplication.run(FifteenthApplication.class, args);
	}

}


В application.properties лежат данные для подключения к Postgre:
spring.datasource.url=jdbc:postgresql://localhost:1234/javatasks
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.datasource.username=postgres
spring.datasource.password=123
spring.jpa.generate-ddl=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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.6.6</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>ru.mirea</groupId>
	<artifactId>fifteenth</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>fifteenth</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>11</java.version>
	</properties>
	<dependencies>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.postgresql</groupId>
			<artifactId>postgresql</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.hibernate.orm/hibernate-core -->
		<dependency>
			<groupId>org.hibernate.orm</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>6.0.0.Final</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
			<version>2.6.6</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>5.6.8.Final</version>
		</dependency>


	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
		<resources>
			<resource>
				<directory>resources</directory>
				<targetPath>${project.build.outputDirectory}</targetPath>
				<includes>
					<include>application.properties</include>
				</includes>
			</resource>
		</resources>
	</build>
</project>


По идее всё должно работать, но при запуске spring boot, вылетает следующая ошибка:

2022-04-19 16:36:52.368  WARN 17568 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authorController': Unsatisfied dependency expressed through field 'authorRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authorRepo' defined in ru.mirea.fifteenth.AuthorRepo defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot create inner bean '(inner bean)#139fb87f' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#139fb87f': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
2022-04-19 16:36:52.375  INFO 17568 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2022-04-19 16:36:52.439  INFO 17568 --- [  restartedMain] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-04-19 16:36:52.527 ERROR 17568 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field authorRepo in ru.mirea.fifteenth.AuthorController required a bean named 'entityManagerFactory' that could not be found.

The injection point has the following annotations:
	- @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.


Process finished with exit code 0


Я понимаю, что программа не может найти бин, но опять же в официальном гайде ничего про это нет. При гуглении выскакивали совсем странные решения, которые не помогают. Так что же делать?
  • Вопрос задан
  • 4340 просмотров
Решения вопроса 1
azerphoenix
@azerphoenix Куратор тега Java
Java Software Engineer
Добрый день.
Уберите:
<!-- https://mvnrepository.com/artifact/org.hibernate.orm/hibernate-core -->
    <dependency>
      <groupId>org.hibernate.orm</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>6.0.0.Final</version>
    </dependency>
 <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>5.6.8.Final</version>
    </dependency>


Также вы можете удалить version отсюда:
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
      <version>2.6.6</version>
    </dependency>


Попробуйте перезапустить приложение. Вот. похожая проблема: https://stackoverflow.com/questions/42182426/sprin...
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
Bell Integrator Хабаровск
До 400 000 ₽
Bell Integrator Ульяновск
До 400 000 ₽
Bell Integrator Ижевск
До 400 000 ₽