NoSuchBeanDefinitionException при создании простого проекта Spring JPA

1

Я следую следующему руководству: https://spring.io/guides/gs/accessing-data-jpa/

Я использую maven, Spring и JPA для создания базы данных, основанной на выборке. У меня есть следующие классы;

Модельный класс:

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

@Entity
public class Customer {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;
    public long getId() { return this.id; }
    public void setId(long Id) { this.id = Id; }

    private String firstName;
    public String getFirstName() { return this.firstName; }
    public void setFirstName(String FirstName) { this.firstName = FirstName; }

    private String lastName;
    public String getLastName() { return this.lastName; }
    public void setLastName(String LastName) { this.lastName = LastName; }

    public Customer(String firstname, String lastname) {
        super();
        this.firstName = firstname;
        this.lastName = lastname;
    }

    public Customer() {
        super();
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%d, firstName='%s', lastName='%s']",
                id, firstName, lastName);
    }
}

Класс CustomerRepository

import java.util.List;

import org.springframework.data.repository.CrudRepository;

import com.accenture.cursojava.modelos.Customer;

public interface CustomerRepository extends CrudRepository<Customer, Long>{
    List<Customer> findByLastName(String lastName);
}

Класс применения:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;

import com.accenture.cursojava.dataaccess.CustomerRepository;
import com.accenture.cursojava.modelos.Customer;

@Configuration
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
        CustomerRepository repository = context.getBean(CustomerRepository.class);
        repository.save(new Customer("Cliente", "de Prueba 1"));
        repository.save(new Customer("Cliente", "de Prueba 2"));
        repository.save(new Customer("Cliente", "de Prueba 3"));
        repository.save(new Customer("Cliente", "de Prueba 4"));
        repository.save(new Customer("Cliente", "de Prueba 1"));
        repository.save(new Customer("Cliente", "de Prueba 2"));
        repository.save(new Customer("Cliente", "de Prueba 3"));
        repository.save(new Customer("Cliente", "de Prueba 4"));

        Iterable<Customer> clientes = repository.findAll();
        for (Customer customer : clientes) {
            System.out.println(customer.getFirstName());
            System.out.println(customer.getLastName());
        }
        Iterable<Customer> clientes1 = repository.findByLastName("de Prueba 1");
        for (Customer customer : clientes1) {
            System.out.println(customer.getFirstName());
            System.out.println(customer.getLastName());
        }
        context.close();
    }
}

После выполнения кода и последующего выполнения, точно так же, как указано в уроке, я получаю следующий вывод:

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.myapplication.CustomerRepository] is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:319)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:987)
    at com.myapplication.Application.main(Application.java:18)

Любые идеи о том, что может быть виновником?

  • 1
    Чтобы добавить к комментарию Strawberry, столбец типа данных UNIXTIME / DATETIME также можно использовать для определения порядка строк в MySQL @MadhurBhaiya «У вас есть первичный ключ (id), на основе которого можно определить первое значение?» Для этого нужен не только столбец первичного ключа с параметрами auto_increment.
  • 0
    Вы реализовали интерфейс? Я не верю, что вы можете создавать экземпляры интерфейсов ...
Показать ещё 2 комментария
Теги:
maven
spring
jpa

1 ответ

1
Лучший ответ

Весна ничего не знает об этом компоненте CustomerRepository. Вы должны сказать Spring, что это управляемый компонент. Вы можете сделать это, добавив аннотацию @Repository.

@Repository
public interface CustomerRepository extends CrudRepository<Customer, Long>{
    List<Customer> findByLastName(String lastName);
}

Вам также может потребоваться рассказать Spring, где искать аннотированные классы (хотя, возможно, @EnableAutoConfiguiration делает ненужным - я не знаком с ним)

@Configuration
@EnableAutoConfiguration
@EnableJpaRepositories()//specify the base package containing your repository interfaces.
public class Application {

}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню