Spring - поле требует тип бина, который не может быть найден - PullRequest
0 голосов
/ 24 мая 2018

Я пытаюсь написать простое приложение Spring (с Maven), которое будет подключаться к базе данных mLab mongoDB, но когда я пытаюсь запустить его, появляется сообщение об ошибке:

*************************** Приложение не удалось запустить


Описание:

Полевой автомобильСервис на главной.Controller.CarController требуется компонент типа 'main.Service.CarService', который не может быть найден.

Действие:

Рассмотрим определение компонента типа 'main.Service.CarService' вВаша конфигурация.

Я попробовал некоторые методы, которые я нашел в StackOverflow (например, реорганизация структуры проекта), но это не помогло, или я что-то упустил.Это структура моего проекта:

enter image description here

И файлы моего проекта:

Main.java

package main.Controller;

import main.Entity.Car;
import main.Service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

@RestController
@RequestMapping("/cars")

public class CarController {
    @Autowired
    private CarService carService;

    @RequestMapping(method = RequestMethod.GET)
    public Collection<Car> getAllCars(){
        return this.carService.getAllCars();
    }

}

application.properties

server.port = 3000
spring.data.mongodb.uri=mongodb://user:pass@ds211309.mlab.com:11309/cars

CarController.java

package main.Controller;

import main.Entity.Car;
import main.Service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

@RestController
@RequestMapping("/cars")

public class CarController {
    @Autowired
    private CarService carService;

    @RequestMapping(method = RequestMethod.GET)
    public Collection<Car> getAllCars(){
        return this.carService.getAllCars();
    }

}

CarService.java

package main.Service;

import main.Dao.CarRepository;
import main.Entity.Car;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;

public class CarService {

    @Autowired
    private CarRepository carRepo;

    public Collection<Car> getAllCars() {
        return carRepo.findAll();
    }
}

CarRepository.java

package main.Dao;

import main.Entity.Car;
import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.List;

public interface CarRepository extends MongoRepository<Car, String> {

    public Car findByModel(String model);
    public List<Car> findByMake(String make);
}

Car.java

package main.Entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import java.util.Date;

@Document(collection = "cars")
public class Car {

    @Id
    public String id;

    public String make;
    public String model;
    public String body;
    public String engine;
    public int totalRentals;
    public int seats;
    public int price;
    public double totalIncome;
    public Date updated_date;

    public Car(String id, String make, String model, String body, String engine, int totalRentals, int seats, int price, double totalIncome, Date updated_date) {
        this.id = id;
        this.make = make;
        this.model = model;
        this.body = body;
        this.engine = engine;
        this.totalRentals = totalRentals;
        this.seats = seats;
        this.price = price;
        this.totalIncome = totalIncome;
        this.updated_date = updated_date;
    }

    @Override
    public String toString() {
        return String.format(
                "Car[id=%s, make='%s', model='%s', body='%s', engine='%s', totalRentals='%s', seats='%s', price='%s', totalIncome='%s', updated_date='%s']",
                id, make, model, body, engine, totalRentals, seats, price, totalIncome, updated_date);
    }



}

Pom.xml

<?xml version="1.0" encoding="UTF-8"?>

http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0

<groupId>com.gdyniarent</groupId>
<artifactId>GdyniaRent backend API</artifactId>
<version>1.0-SNAPSHOT</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.2.RELEASE</version>
</parent>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

</dependencies>

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

<repositories>
    <repository>
        <id>spring-releases</id>
        <name>Spring Releases</name>
        <url>https://repo.spring.io/libs-release</url>
    </repository>

</repositories>

<pluginRepositories>
    <pluginRepository>
        <id>spring-releases</id>
        <name>Spring Releases</name>
        <url>https://repo.spring.io/libs-release</url>
    </pluginRepository>

</pluginRepositories>

1 Ответ

0 голосов
/ 24 мая 2018

public class CarService { - просто обычное pojo.

Отметить его как боб:

@Service
public class CarService {
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...