0

Подскажите пожалуйста. Не понимаю в чем проблема, делаю всё по уроку, но ловлю такую ошибку:

Description:

Field userRepository in com.test.api.controller.TestController required a bean of type 'com.test.api.repository.UserRepository' 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 of type 'com.test.api.repository.UserRepository' in your configuration.

Application file:

package com.test.api;

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

@SpringBootApplication
public class ApiApplication {

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

}

Model:

package com.test.api.models;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
import java.util.Date;

@Entity
@Table(name = "user")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
        allowGetters = true)
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank
    private String login;

    @NotBlank
    private String password;

    @NotBlank
    @Email
    private String email;

    @Column(nullable = false, updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @CreatedDate
    private Date createdAt;

    @Column(nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @LastModifiedDate
    private Date updatedAt;
}

Controller:

package com.test.api.controller;

import com.test.api.exception.ResourceNotFoundException;
import com.test.api.models.User;
import com.test.api.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api")
public class TestController {

    @Autowired
    UserRepository userRepository;

    // Get All Notes
    @GetMapping("/users")
    public List<User> getAllNotes() {
        return userRepository.findAll();
    }
}

Repository:

package com.test.api.repository;

import com.test.api.models.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;


@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

Properties:

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
# MySQL properties
spring.datasource.url = jdbc:mysql://localhost:3306/test?useSSL=false
spring.datasource.username = root
spring.datasource.password = 1234

## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update

Сборщик проекта - gradle.

1
  • Перед классом ApiApplication напишите аннотацию @ComponentScan и как параметр укажите основной пакет. По основным имею в виду тот в котором лежат классы распреледенные по пакетам. К примеру com.example
    – Tsyklop
    21 дек 2018 в 23:00

1 ответ 1

0

Включить надо

@SpringBootApplication
@EnableJpaRepositories("com.test.api.repository")
public class ApiApplication {
    public static void main(String[] args) {
        SpringApplication.run(ApiApplication.class, args);
    }
}
2
  • Спасибо, помогло от части. Сейчпсй вылезла такая ошибка: Description: Field userRepository in com.test.api.controller.TestController required a bean named 'entityManagerFactory' that could not be found. 22 дек 2018 в 16:21
  • В Spring Boot такая ошибка обычно обозначает, что в зависимости не добавлены нужные библиотеки. Но это уже другая проблема, для которой нужен отдельный вопрос. 22 дек 2018 в 16:32

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.