簡體   English   中英

REST API 中創建bean名時出現UnsatisfiedDependencyException錯誤

[英]UnsatisfiedDependencyException error in creating bean name in REST API

** 2021-11-26 20:30:57.375 WARN 11700 --- [restartedMain] ConfigServletWebServerApplicationContext:上下文初始化期間遇到異常 - 取消刷新嘗試:org.springframework.beans.factory.UnsatisfiedDependencyException:創建名稱為“bookRestController”的 bean 時出錯:通過字段“bookService”表達的不滿足的依賴關系; 嵌套的異常是 org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookServiceImpl': Unsatisfied dependency expressed through field 'bookService'; 嵌套異常是 org.springframework.beans.factory.BeanCurrentlyInCreationException:創建名稱為“bookServiceImpl”的 bean 時出錯:當前正在創建請求的 bean:是否存在無法解析的循環引用? 2021-11-26 20:30:57.376 INFO 11700 --- [restartedMain] j.LocalContainerEntityManagerFactoryBean: Closing JPA EntityManagerFactory for persistence unit 'default' 2021-11-26 20:30:57.382 INFO 11700 --- 8 [restarted1708] 88 [restarted1708] JPA EntityManagerFactory .zaxxer.hikari.HikariDataSource:HikariPool-1 - 關閉已啟動... 2021-11-26 20:30:57.393 INFO 11700 --- [restartedMain] com.zaxxer.hikari.HikariDataSource:HikariPool-1 - 關閉已完成。 2021-11-26 20:30:57.396 INFO 11700 --- [restartedMain] o.apache.catalina.core.StandardService:停止服務[Tomcat] 2021-11-26 20:30:57.410 INFO 11700 --- [restartedMain ] ConditionEvaluationReportLoggingListener:

啟動 ApplicationContext 時出錯。 要顯示條件報告,請在啟用“調試”的情況下重新運行您的應用程序。 2021-11-26 20:30:57.437 錯誤 11700 --- [restartedMain] osbdLoggingFailureAnalysisReporter:**


應用程序啟動失敗


描述:

application context中的一些bean的依賴關系形成了一個循環:

bookRestController(字段私有 BookAuthorManyToManyRelationship.service.BookService BookAuthorManyToManyRelationship.Rest.BookRestController.bookService)┌──────┐ | bookServiceImpl(字段私有 BookAuthorManyToManyRelationship.service.BookService BookAuthorManyToManyRelationship.serviceImpl.BookServiceImpl.bookService)└──────┘

行動:

不鼓勵依賴循環引用,默認情況下它們是被禁止的。 更新您的應用程序以刪除 bean 之間的依賴循環。 作為最后的手段,可以通過將 spring.main.allow-circular-references 設置為 true 來自動打破循環。*

BasicProjectApplication.java

```package BookAuthorManyToManyRelationship;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
public class BasicProjectApplication {

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

}```

**AuthorDAO.java**
```package BookAuthorManyToManyRelationship.dao;

import java.util.List;

import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;

public interface AuthorDAO {
    public Author findById(int id);
    public List<Book> findListOfBookWrittenByAuthor();
    public void deleteById(int id);
    public void save(Author author);
}```

**BookDAO.java**

```package BookAuthorManyToManyRelationship.dao;

import java.util.List;

import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;

public interface BookDAO {
    public Book findById(int id);
    public List<Author> findListOfAuthorWhoHasWrittenThisBook();
    public void deleteById(int id);
    public void save(Book book);
}```

**AuthorDAOImpl.java**

```package BookAuthorManyToManyRelationship.daoImpl;

import java.util.List;

import javax.persistence.EntityManager;

import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import BookAuthorManyToManyRelationship.dao.AuthorDAO;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
@Repository
public class AuthorDAOImpl implements AuthorDAO {
    @Autowired
    private EntityManager entityManager;

    @Override
    public Author findById(int id) {
        Session session = entityManager.unwrap(Session.class);
        Author author = session.get(Author.class, id);
        
        return author;
    }

    @Override
    public List<Book> findListOfBookWrittenByAuthor() {
        
        Session session = entityManager.unwrap(Session.class);
        Query<Book> theQuery = session.createQuery("from Book",Book.class);
        
        List<Book> book = theQuery.getResultList();
        return book;
    }

    @Override
    public void deleteById(int id) {
        
        Session session = entityManager.unwrap(Session.class);
        
        Query theQuery = session.createQuery("delete from Author where author_id=:theid");
        theQuery.setParameter("theid", id);
        theQuery.executeUpdate();
    }

    @Override
    public void save(Author author) {
        Session session = entityManager.unwrap(Session.class);
        session.saveOrUpdate(author);
    }

}```
**BookDAOImpl.java**

```package BookAuthorManyToManyRelationship.daoImpl;

import java.util.List;

import javax.persistence.EntityManager;

import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import BookAuthorManyToManyRelationship.dao.BookDAO;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
@Repository
public class BookDAOImpl implements BookDAO {
    
    @Autowired
    private  EntityManager  entityManager;

    @Override
    public Book findById(int id) {
        
        Session session = entityManager.unwrap(Session.class);
        Book b = session.get(Book.class, id);
        return b;
    }

    @Override
    public List<Author> findListOfAuthorWhoHasWrittenThisBook() {
        
        Session session = entityManager.unwrap(Session.class);
        Query<Author> q = session.createQuery("from Author",Author.class);
        List<Author> author = q.getResultList();
        return author;
    }

    @Override
    public void deleteById(int id) {
        
        Session session = entityManager.unwrap(Session.class);
        Query q = session.createQuery("delete from Book where book_id:=theid");
        q.setParameter("theid", id);
        q.executeUpdate();
    }

    @Override
    public void save(Book book) {
        
        Session session = entityManager.unwrap(Session.class);
        session.saveOrUpdate(book);
        
    }

}```

**Address.java**

```package BookAuthorManyToManyRelationship.entity;

import javax.persistence.Embeddable;

@Embeddable
public class Address {
    String street;
    String city;
    String country;
    public Address(String street, String city, String country) {
        super();
        this.street = street;
        this.city = city;
        this.country = country;
    }
    public Address() {
        super();
        // TODO Auto-generated constructor stub
    }
    public String getStreet() {
        return street;
    }
    public void setStreet(String street) {
        this.street = street;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }
    
}```
**Author.java**

```package BookAuthorManyToManyRelationship.entity;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name="author")
public class Author {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    int id;
    String authorName;
    Address address;
    @ManyToMany(cascade = CascadeType.ALL)
    List<Book> book;
    public Author() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Author(int id, String authorName,Address address,List<Book> book) {
        super();
        this.id = id;
        this.authorName = authorName;
        this.address = address;
        this.book = book;
    }
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getAuthorName() {
        return authorName;
    }
    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public List<Book> getBook() {
        return book;
    }
    public void setBook(List<Book> book) {
        this.book = book;
    }
    
}```
**Book.java**

```package BookAuthorManyToManyRelationship.entity;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name="book")
public class Book {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    int id;
    String book_name;
    String subject;
    @ManyToMany(cascade = CascadeType.ALL)
    List<Author> author;
    public Book() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Book(int id, String book_name, String subject, List<Author> author) {
        super();
        this.id = id;
        this.book_name = book_name;
        this.subject = subject;
        this.author = author;
    }
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getBook_name() {
        return book_name;
    }
    public void setBook_name(String book_name) {
        this.book_name = book_name;
    }
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public List<Author> getAuthor() {
        return author;
    }
    public void setAuthor(List<Author> author) {
        this.author = author;
    }
    
    
}```

**AuthorRestController**

```package BookAuthorManyToManyRelationship.Rest;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
import BookAuthorManyToManyRelationship.service.AuthorService;

@RestController
@RequestMapping("/welcome")
public class AuthorRestController {
    
    @Autowired
    private AuthorService authorService;
    

    @GetMapping("/author/{id}")
    public Author getAuthorById(@PathVariable int id )
    {
        return authorService.findById(id);
    }
    
    
    @GetMapping("/book")
    public List<Book> getBook()
    {
        return authorService.findListOfBookWrittenByAuthor();
    }
    
    @PostMapping("/saveAuthor")
    public void setAuthor(@RequestBody Author author)
    {
        authorService.save(author);
    }
    
    
}```

**BookRestController.java**

```package BookAuthorManyToManyRelationship.Rest;

import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
import BookAuthorManyToManyRelationship.service.BookService;

@RestController
@RequestMapping("/abc")
public class BookRestController {
    
    @Autowired
    private BookService bookService;
    
    
    @GetMapping("/book/{id}")
    public Book getBookById(@PathVariable int id )
    {
        return bookService.findById(id);
    }
    
    @GetMapping("/author")
    public List<Author> getAuthor()
    {
        return bookService.findListOfAuthorWhoHasWrittenThisBook();
    }
    
    
    @PostMapping("/saveBook")
    public void setBook(@RequestBody Book book)
    {       
        bookService.save(book);
    }
    
}```

**AuthorService.java**

```package BookAuthorManyToManyRelationship.service;

import java.util.List;


import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;

public interface AuthorService {
    public Author findById(int id);
    public List<Book> findListOfBookWrittenByAuthor();
    public void deleteById(int id);
    public void save(Author author);
}```

**BookService.java**

```package BookAuthorManyToManyRelationship.service;

import java.util.List;

import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
public interface BookService {

    public Book findById(int id);
    public List<Author> findListOfAuthorWhoHasWrittenThisBook();
    public void deleteById(int id);
    public void save(Book book);
    
}```

**AuthorServiceImpl.java**

```package BookAuthorManyToManyRelationship.serviceImpl;

import java.util.List;

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

import BookAuthorManyToManyRelationship.dao.AuthorDAO;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
import BookAuthorManyToManyRelationship.service.AuthorService;
@Service
public class AuthorServiceImpl implements AuthorService {

    @Autowired
    private AuthorDAO authorDAO;
    
    
    @Override
    @Transactional
    public Author findById(int id) {
        return authorDAO.findById(id);
    }

    @Override
    @Transactional
    public List<Book> findListOfBookWrittenByAuthor() {
        return authorDAO.findListOfBookWrittenByAuthor();
    }

    @Override
    @Transactional
    public void deleteById(int id) {
        authorDAO.deleteById(id);
    }

    @Override
    @Transactional
    public void save(Author author) {
        authorDAO.save(author);
    }

}```

**BookServiceImpl.java**

```package BookAuthorManyToManyRelationship.serviceImpl;

import java.util.List;


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

import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
import BookAuthorManyToManyRelationship.service.BookService;
@Service
public class BookServiceImpl implements BookService {
    
    @Autowired
    private BookService bookService;
    

    @Override
    @Transactional
    public Book findById(int id) {
        return bookService.findById(id);
    }

    @Override
    @Transactional
    public List<Author> findListOfAuthorWhoHasWrittenThisBook() {
        return bookService.findListOfAuthorWhoHasWrittenThisBook();
    }

    @Override
    @Transactional
    public void deleteById(int id) {
        bookService.deleteById(id);
    }

    @Override
    @Transactional
    public void save(Book book) {
        bookService.save(book);
    }
    
}
```

你混合spring-data-jpahibernate 使用JPAHibernate 下面我給你一個更好的例子,如何使用spring data jpa Hibernate also use here for relational mapping and create table but for business logic use spring data jpa built-in method like save() , findAll() , deleteById() , findById() etc... using jpaRepository . 並且始終使用private訪問修飾符在實體中聲明變量,因為它可以保護您的數據。

下面是我的代碼:

地址

@Embeddable
public class Address {
    private String street;
    private String area;
    private String stat;
        
    // getter and setter with constructor
}

作者

@Entity
@Table(name="author")
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String authorName;

    @Embedded
    private Address address;

    @ManyToMany(targetEntity = Book.class, cascade = CascadeType.ALL)
    private List<Book> book;

    // getter and setter with constructor
        
}

@Entity
@Table(name="book")
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String book_name;
    private String subject;

    @ManyToMany(targetEntity = Author.class, mappedBy = "book", cascade = CascadeType.ALL)
    private List<Author> author;
        
    // getter and setter with constructor
}

存儲庫1

@Repository
public interface AuthorRepo extends JpaRepository<Author, Integer>{

}

存儲庫2

@Repository
public interface BookRepo extends JpaRepository<Book, Integer>{

}

作者服務

public interface AuthorService {
     public Author findById(int id);
     public List<Book> findListOfBookWrittenByAuthor();
     public void deleteById(int id);
     public void save(Author author);
}

圖書服務

public interface BookService {    
     public Book findById(int id);
     public List<Author> findListOfAuthorWhoHasWrittenThisBook();
     public void deleteById(int id);
     public void save(Book book);        
}

作者 Impl

    @Service
    public class AuthorServiceImpl implements AuthorService {
    
        @Autowired
        private AuthorRepo authorRepo;
            
        @Override
        public Author findById(int id) {
            return authorRepo.findById(id).get();
        }
    
        @Override
        public List<Author> findListOfAuthorWhoHasWrittenThisBook() {
            return authorRepo.findAll();
        }
    
        @Override
        public void deleteById(int id) {
            authorRepo.deleteById(id);
        }
    
        @Override
        public void save(Author author) {
            authorRepo.save(author);
        }
    
    }

圖書實施

    @Service
    public class BookServiceImpl implements BookService {
        
        @Autowired
        private BookRepo bookRepo;    
    
        @Override
        public Book findById(int id) {
            return bookRepo.findById(id).get();
        }
    
        @Override
        public List<Book> findListOfBookWrittenByAuthor() {
            return bookRepo.findAll();
        }
    
        @Override
        public void deleteById(int id) {
            bookRepo.deleteById(id);
        }
    
        @Override
        public void save(Book book) {
            bookRepo.save(book);
        }
        
    }

Rest 控制器1

 @RestController
    @RequestMapping("/welcome")
    public class AuthorRestController {
        
        @Autowired
        private AuthorService authorService;
        
    
        @GetMapping("/author/{id}")
        public Author getAuthorById(@PathVariable int id )
        {
            return authorService.findById(id);
        }
        
        
        @GetMapping("/author")
        public List<Author> getAuthor()
        {
            return authorService.findListOfAuthorWhoHasWrittenThisBook();
        }
        
        @PostMapping("/saveAuthor")
        public void setAuthor(@RequestBody Author author)
        {
            authorService.save(author);
        }
           
    }

Rest 控制器2

@RestController
    @RequestMapping("/abc")
    public class BookRestController {
        
        @Autowired
        private BookService bookService;
        
        
        @GetMapping("/book/{id}")
        public Book getBookById(@PathVariable int id )
        {
            return bookService.findById(id);
        }
        
        @GetMapping("/book")
        public List<Book> getBook()
        {
            return bookService.findListOfBookWrittenByAuthor();
        }
        
        
        @PostMapping("/saveBook")
        public void setBook(@RequestBody Book book)
        {       
            bookService.save(book);
        }
        
    }

這是你的問題的原因

@Service
public class BookServiceImpl implements BookService {
    
@Autowired
private BookService bookService

我無法理解為什么你在它自己的實現中引用了BookService ,我最好的猜測是你想在這里添加BookDAO

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM