Spring Boot @Autowired does not work with Repository

Asked

Viewed 333 times

0

I have the following mistake:

Description:

Field categoriaRepository in 
com.algaworks.algamoneyapi.resource.CategoriaResource 
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.

Code of the main project class:

package com.algaworks.algamoneyapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableJpaRepositories
public class AlgamoneyApiApplication {

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

}

Code of the Entity:

package com.algaworks.algamoneyapi.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Objects;

@Entity
@Table(name = "categoria")
public class Categoria {

    @Id
    @GeneratedValue
    private Long codigo;
    private String nome;

    public Long getCodigo() {
        return codigo;
    }

    public void setCodigo(Long codigo) {
        this.codigo = codigo;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Categoria categoria = (Categoria) o;
        return Objects.equals(codigo, categoria.codigo);
    }

    @Override
    public int hashCode() {
        return Objects.hash(codigo);
    }
}

Repository code:

package com.algaworks.algamoneyapi.repository;

import com.algaworks.algamoneyapi.model.Categoria;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;


@Repository
public interface CategoriaRepository extends JpaRepository<Categoria, Long> {
}

Controller Code:

package com.algaworks.algamoneyapi.resource;

import com.algaworks.algamoneyapi.model.Categoria;
import com.algaworks.algamoneyapi.repository.CategoriaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/categorias")
public class CategoriaResource {

    @Autowired
    private CategoriaRepository categoriaRepository;


    @GetMapping
    public List<Categoria> listar() {
        return categoriaRepository.findAll();
    }
}

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.4.4</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.algaworks</groupId>
    <artifactId>algamoney-api</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>algamoney-api</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <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.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Project structure:

Estrutura do projeto

I’ve tried to:

  • @EnableJpaRepositories(basePackages = "com.algaworks.algamoney.repository")
  • @ComponentScan(basePackages = "com.algaworks")
  • @SpringBootApplication(scanBasePackages = {"com.algaworks"})

but nothing works.

  • Hello, not sure but try changing the note @Autowired for @Repository and remove the latter from the interface statement CategoriaRepository. I think the note @Repository shall be applied to non-local variables, which already @Autowired, and produces (instance) a default repository implementation for any variable of type JpaRepository or of some sub-interface of the same. I guess I got it right?

  • 1

    Let’s see if I got it right: Swap in Categoriaresource the @Autowired annotation by @Repository? But it gives syntax error: @Repository' not applicable to field. I believe I am correct about instantiating the implementation of a Repository who tells spring to do this is the annotation @Autowired.

  • You’re right, I was wrong. I don’t know much about Spring. @Repository understatement @Component and not @Autowired. I understood what you meant by syntax error, but I think the error is semantic.

  • Yes, semantic! kk

1 answer

0


Apparently the repository is not being loaded in the context of Spring. To do this, the annotation is used @EnableJpaRepositories. There are some ways to do this, I believe in your case the simplest are:

  • Add @EnableJpaRepositories in AlgamoneyApiApplication. By convention, Springboot will scan all classes by @Repository when starting its application, and will include it in the context of Spring;

  • Your attempt: to add @EnableJpaRepositories(basePackages = "com.algaworks.algamoneyapi.repository") in AlgamoneyApiApplication. However, note the package: your repository is on com.algaworks.algamoneyapi.repository and you tried with com.algaworks.algamoney.repository. Probably why it didn’t work.

  • 1

    It also seemed strange not to work without additional modifications, because, as far as I know, for the purpose of mapping repositories is scanned the entire tree of subdirectories/subpackages from what has the class annotated with @SpringBootApplication.

  • Still giving error, but different now. &#xA;Description:&#xA;&#xA;Field categoriaRepository in com.algaworks.algamoneyapi.resource.CategoriaResource required a bean named 'entityManagerFactory' that could not be found.&#xA;&#xA;The injection point has the following annotations:&#xA; - @org.springframework.beans.factory.annotation.Autowired(required=true)&#xA;&#xA;&#xA;Action:&#xA;&#xA;Consider defining a bean named 'entityManagerFactory' in your configuration.&#xA;&#xA;Disconnected from the target VM, address: '127.0.0.1:53194', transport: 'socket'&#xA;&#xA;Process finished with exit code 0&#xA;

  • 1

    @Alineavila If you solved the first problem, I think it is convenient to accept the answer given (and, when you have more points, positive). Here is one problem at a time (that is, by question). I saw that you did not do the [tour], I recommend doing.

  • @Piovezan answer accepted.

  • @Alineavila Thanks if you can add your file pom.xml It was my failure not to ask. There for your next problem I think that to save copy-and-paste you can link this question in the new one you will eventually do.

  • @Piovezan from what I understand, was not used the @EnableJpaRepositories without the basePackages, the error was that a wrong package was forced

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.