Нужна помощь! Spring Boot error: неудовлетворительное DependancyException: ошибка создания бина с именем '' - PullRequest
1 голос
/ 29 октября 2019

Я не могу понять эту ошибку:

org.springframework.beans.factory.UnsatisfiedDependencyException: Ошибка при создании bean-компонента с именем «restapiApplication»: неудовлетворенная зависимость, выраженная через метод «productRepository», параметр 0;вложенное исключение: org.springframework.beans.factory.BeanCreationException: ошибка создания бина с именем productRepository: сбой вызова метода init;вложенное исключение - java.lang.IllegalArgumentException: не удалось создать запрос для метода public abstract com.murphy.demo.model.Product com.murphy.demo.repository.ProductRepository.findOne (java.lang.String)! Не найдено свойство findOne для типа Product!

Вот мой репозиторий в пакете:


    package com.murphy.demo.repository;

    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.stereotype.Repository;
    import org.springframework.stereotype.Service;

    import com.murphy.demo.model.Product;


    @Repository

    public interface ProductRepository extends JpaRepository<Product,String> {

        Product findOne(String id);


    }


    package com.murphy.demo.Controller;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;

    import com.murphy.demo.model.Product;
    import com.murphy.demo.repository.ProductRepository;

    @RestController
    @RequestMapping(path ="/api/products/" )
    public class ProductsController {

        private ProductRepository productRepository;


        @Autowired
        public void productRepository(ProductRepository productRepository) {
            this.productRepository = productRepository;
        }



        @RequestMapping(path ="{id}", method = RequestMethod.GET)
        public Product getProduct(@PathVariable(name = "id") String id) {

            return productRepository.findOne(id);

        }









    }

Product.java в пакете


    package com.murphy.demo.model;

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

    import org.hibernate.annotations.GenericGenerator;



    @Entity
    public class Product {


        @Id
        @GeneratedValue(strategy = GenerationType.AUTO, generator ="system-uuid")
        @GenericGenerator(name ="system-uuid",strategy ="uuid")
        private String id;
        private String name;
        private String description;
        private String category;
        private String type;


        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getDescription() {
            return description;
        }
        public void setDescription(String description) {
            this.description = description;
        }
        public String getCategory() {
            return category;
        }
        public void setCategory(String category) {
            this.category = category;
        }
        public String getType() {
            return type;
        }
        public void setType(String type) {
            this.type = type;
        }

    }

основное приложение:


    package com.murphy.demo;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.autoconfigure.domain.EntityScan;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

    import com.murphy.demo.model.Product;
    import com.murphy.demo.repository.ProductRepository;



    @SpringBootApplication

    public class RestapiApplication  implements CommandLineRunner{



        private ProductRepository productRepository;


        @Autowired
        public void productRepository(ProductRepository productRepository) {
            this.productRepository = productRepository;
        }



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

        @Override
        public void run(String... args) throws Exception {
            Product test = new Product();
            test.setName("test");
            test.setDescription("test");
            test.setCategory("general");
            test.setType("null");


            productRepository.save(test);


        }



    }

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.2.0.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.murphy.demo</groupId>
        <artifactId>restapi</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>restapi</name>
        <description> project for Spring Boot</description>

        <properties>
            <java.version>1.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>com.h2database</groupId>
                <artifactId>h2</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>

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

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

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

            </dependency>


        </dependencies>

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

    </project>

Application.properites выглядит следующим образом:


    spring.h2.console.enabled=true
    spring.datasource.url=jdbc:h2:file:~/Products;IFEXISTS=FALSE;DB_CLOSE_DELAY=-1
    spring.datasource.driverClassName=org.h2.Driver
    spring.datasource.username=sa
    spring.datasource.password=
    spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
    spring.h2.console.path=/h2-console
    spring.jpa.show-sql= true

Я перепробовал все, что мог придумать, Любые предложения на всехбудет полезно.

Спасибо!

Ответы [ 2 ]

1 голос
/ 29 октября 2019

Называя ваш метод " findOne ", JPA Spring Data пытается создать запрос для поиска свойства " findOne " в вашем классе продукта, который несуществует, следовательно, ошибка «Не найдено свойство findOne для типа Product» . Вы должны указать название свойства, которое вы ищете. В вашем случае: findOneById (String id) создаст запрос для поиска одного объекта по свойству Id.

Для получения дополнительной информации о том, как называть методы для создания правильных запросов, вы можете прочитать документацию об этой теме.

0 голосов
/ 29 октября 2019

Почему вы не используете CrudRepository вместо JpaRepository? findOne (id) будет автоматически доступен. Таким образом, ваш интерфейс хранилища будет просто пустым.

https://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html

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