Использование @Autowire для связи моего класса @Service и класса @Repository вызывает ошибку. Не могу найти решение - PullRequest
0 голосов
/ 14 марта 2020

РЕДАКТИРОВАТЬ Решены проблемы из-за неправильного импорта библиотеки постоянства для моих аннотаций. КОНЕЦ РЕДАКТИРОВАНИЯ

Я предоставляю весь свой код для папки «Категория», в которой у меня возникают проблемы, а также файл основного приложения. Для файла "CategoryRepository. java" я также пытался использовать аннотацию @Repository, и это ничего не изменило.

DemoApplication. java

package com.learn.servlocal;

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

@SpringBootApplication
public class DemoApplication {

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

}

Категория. java

// Category Model
package com.learn.servlocal.category;

import javax.persistence.GeneratedValue;
import com.learn.servlocal.relations.Entity;
import com.learn.servlocal.relations.Id;
import com.learn.servlocal.relations.Table;
import lombok.Getter;
import lombok.Setter;

@Entity
@Table(name = "Categories")
public class Category {
    @Id @GeneratedValue
    @Getter @Setter private String id;
    @Getter @Setter private String category;

    public Category(String id, String category){
        super();
        this.id = id;
        this.category = category;
    }

    public Category(){

    }
}

КатегорияСервис. java

// Category service to execute all GET, POST, PUT, and DELETE methods
package com.learn.servlocal.category;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryService {

    @Autowired
    private CategoryRepository categoryRepository;

    // GET method to retrieve all the categories
    public List<Category> getAllCategories() {
        return (List<Category>)categoryRepository.findAll();
    }

    // GET method for a single category
    public Optional<Category> getCategory(String id) {
        return categoryRepository.findById(id);
    }

    // POST method to add a category
    public void addCategory(Category newCategory) {
        categoryRepository.save(newCategory);
    }

    // PUT method to update a category
    public void updateCategory(String id, Category updatedCategory) {
        Optional<Category> oldCategory = categoryRepository.findById(id);
        oldCategory.ifPresent(newCategory -> categoryRepository.save(newCategory));
    }

    // DELETE method to delete a category
    public void deleteCategory(String id) {
        categoryRepository.deleteById(id);     
    }    
}

КатегорияКонтроллер . java

package com.learn.servlocal.category;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CategoryController {

    @Autowired
    CategoryService categoryService;

    @RequestMapping("/categories")
    public List<Category> getAllCategories(){
        return categoryService.getAllCategories();
    }

    @RequestMapping(value="/categories", method=RequestMethod.POST)
    public void addCategory(@RequestBody Category newCategory) {
        categoryService.addCategory(newCategory);
    }
}

CategoryRepository. java

package com.learn.servlocal.category;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;

@Component
public interface CategoryRepository extends CrudRepository<Category, String> {

}

Консоль отладки

:: Spring Boot ::        (v2.2.5.RELEASE)

2020-03-13 16:25:48.087  INFO 9308 --- [  restartedMain] com.learn.servlocal.DemoApplication      : Starting DemoApplication on DESKTOP-MCL2D2J with PID 9308 (started by emman in c:\Users\emman\Documents\Entreprenuer Craigslist 2.0\servlocal)
2020-03-13 16:25:48.087  INFO 9308 --- [  restartedMain] com.learn.servlocal.DemoApplication      : No active profile set, falling back to default profiles: default
2020-03-13 16:25:48.232  INFO 9308 --- [  restartedMain] o.s.b.devtools.restart.ChangeableUrls    : The Class-Path manifest attribute in C:\Users\emman\.m2\repository\org\glassfish\jaxb\jaxb-runtime\2.3.2\jaxb-runtime-2.3.2.jar referenced one or more files that do not exist: file:/C:/Users/emman/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.xml.bind-api-2.3.2.jar,file:/C:/Users/emman/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/txw2-2.3.2.jar,file:/C:/Users/emman/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/istack-commons-runtime-3.0.8.jar,file:/C:/Users/emman/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/stax-ex-1.8.1.jar,file:/C:/Users/emman/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/FastInfoset-1.2.16.jar,file:/C:/Users/emman/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.activation-api-1.2.1.jar
2020-03-13 16:25:48.233  INFO 9308 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-03-13 16:25:48.233  INFO 9308 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-03-13 16:25:49.027  INFO 9308 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-03-13 16:25:49.092  INFO 9308 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 50ms. Found 1 JPA repository interfaces.
2020-03-13 16:25:50.340  INFO 9308 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8081 (http)
2020-03-13 16:25:50.355  INFO 9308 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-03-13 16:25:50.355  INFO 9308 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.31]
2020-03-13 16:25:50.566  INFO 9308 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-03-13 16:25:50.567  INFO 9308 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2334 ms
2020-03-13 16:25:50.878  INFO 9308 --- [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-03-13 16:25:50.970  INFO 9308 --- [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.4.12.Final
2020-03-13 16:25:51.240  INFO 9308 --- [  restartedMain] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-03-13 16:25:51.394  INFO 9308 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-03-13 16:25:51.925  INFO 9308 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-03-13 16:25:51.955  INFO 9308 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2020-03-13 16:25:52.643  INFO 9308 --- [  restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-03-13 16:25:52.656  INFO 9308 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-03-13 16:25:52.747  INFO 9308 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2020-03-13 16:25:53.059  WARN 9308 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'categoryController': Unsatisfied dependency expressed through field 'categoryService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'categoryService': Unsatisfied dependency expressed through field 'categoryRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'categoryRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.learn.servlocal.category.Category

Любая помощь приветствуется. Спасибо.

Ответы [ 2 ]

3 голосов
/ 14 марта 2020

Когда вы получаете исключение "неуправляемый тип" при попытке создать свой репозиторий, мне кажется, что import в классе категории для ваших постоянных аннотаций неправильно:

import com.learn.servlocal.relations.Entity;
import com.learn.servlocal.relations.Id;
import com.learn.servlocal.relations.Table;

В то время как они должны быть:

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
0 голосов
/ 14 марта 2020

Я уже реализовал проект такой же вашей ситуации. Вы можете сослаться на мой код, надеюсь, у вас есть больше идей для решения вашей проблемы.

Сотрудник. java

package com.tvp.demo.model;

import java.io.Serializable;

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

@Entity
@Table(name = "employee")
public class Employee implements Serializable {

  private static final long serialVersionUID = -8577891700634111561L;

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id", nullable = false)
  private Long id;

  @Column(name = "name", nullable = false)
  private String name;

  @Column(name = "phone")
  private String phone;

  public Employee() {
  }

  public Employee(Long id, String name, String phone) {
    this.id = id;
    this.name = name;
    this.phone = phone;
  }

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getPhone() {
    return phone;
  }

  public void setPhone(String phone) {
    this.phone = phone;
  }

}

EmployeeService. java

package com.tvp.demo.service;

import java.util.List;
import java.util.Optional;

import com.tvp.demo.model.Employee;

public interface EmployeeService {

  Iterable<Employee> findAll();

  List<Employee> search(String s);

  Optional<Employee> findById(Long id);

  void deleteById(Long id);

  void save(Employee employee);
}

EmployeeServiceImpl. java

package com.tvp.demo.service;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tvp.demo.model.Employee;
import com.tvp.demo.repository.EmployeeRepository;

@Service
public class EmployeeServiceImpl implements EmployeeService {

  @Autowired
  private EmployeeRepository employeeRepository;

  @Override
  public Iterable<Employee> findAll() {
    return employeeRepository.findAll();
  }

  @Override
  public List<Employee> search(String s) {
    return employeeRepository.findByNameContaining(s);
  }

  @Override
  public Optional<Employee> findById(Long id) {
    return employeeRepository.findById(id);
  }

  @Override
  public void deleteById(Long id) {
    employeeRepository.deleteById(id);
  }

  @Override
  public void save(Employee employee) {
    employeeRepository.save(employee);
  }

}

EmployeeRepository. java

package com.tvp.demo.repository;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

import com.tvp.demo.model.Employee;

public interface EmployeeRepository extends CrudRepository<Employee, Long> {

    List<Employee> findByNameContaining(String s);

}

EmployeeController. java

package com.tvp.demo.controller;

import com.tvp.demo.service.EmployeeService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.tvp.demo.model.Employee;

@Controller
public class EmployeeController {

  @Autowired
  private EmployeeService employeeService;

  @GetMapping("/employees")
  public Iterable<Employee> all(){
    return employeeService.findAll();
  }

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