this is my first exercise with Spring Boot and this is my application.properties:
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc.mysql://localhost:3306/notedb
spring.datasource.username=root
spring.datasource.password=*******
These are my classes:
DemoMySqlApplication.java
package com.example.demomysql;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
#ComponentScan(basePackages={"com.joydeep.springboot"})
public class DemoMysqlApplication {
public static void main(String[] args) {
SpringApplication.run(DemoMysqlApplication.class, args);
}
NoteRepository.java (interface):
package com.example.demomysql;
import org.springframework.data.repository.CrudRepository;
public interface NoteRepository extends CrudRepository <Note, Integer>{
}
NoteController.java
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 org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#RestController
#RequestMapping(value="/note")
public class NoteController {
#Autowired
private NoteRepository noteRepository;
#GetMapping(value="/all")
public String getAllNotes(Model model) {
model.addAttribute("notes", noteRepository.findAll());
return "list";
}
#GetMapping(value="/debug")
public #ResponseBody Iterable<Note> getNotes(){
return noteRepository.findAll();
}
}
Note.java (Entity class)
package com.example.demomysql;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.springframework.data.repository.CrudRepository;
#Entity
public class Note {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String title;
private String description;
private Boolean done;
public Integer getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getDone() {
return done;
}
public void setDone(Boolean done) {
this.done = done;
}
}
From the console, I don't see errors. Tomcat starts normally. These are the last two information:
Tomcat started on port(s): 8080 (http) with context path ''
Started DemoMysqlApplication in 0.731 seconds (JVM running for 480.726)
But on my MySQL database (I created a DB named "notedb" and a table named "note", before to launch this application). I have one row with the data in note. But when I try to connect to:
http://localhost:8080/note/debug
I see:
I think I have a problem with Controller class.
Please, can you help me?
Thanks
pring.jpa.hibernate.ddl-auto=update
spring.datasource.platform=mysql
spring.datasource.url=jdbc:mysql://localhost:3306/notedb?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=****
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
Remove
exclude={DataSourceAutoConfiguration.class}
#ComponentScan(basePackages={"com.joydeep.springboot"})
Keep #RestController remove #ResponseBody
For #Controller keep #ResponseBody or ResponseEntity<T>
Change return type Iterable<Note> to List<Note>
Application
#SpringBootApplication
public class DemoMysqlApplication {
public static void main(String[] args) {
SpringApplication.run(DemoMysqlApplication.class, args);
}
Rest Controller
#RestController
#RequestMapping(value="/note")
public class NoteController {
#Autowired
private NoteRepository noteRepository;
#GetMapping(value="/debug")
public List<Note> getNotes(){
return noteRepository.findAll();
}
}
Controller
#Controller
#RequestMapping(value="/note")
public class NoteController {
#Autowired
private NoteRepository noteRepository;
#GetMapping(value="/debug")
public ResponseEntity<List<Note>> getNotes(){
return new ResponseEntity<List<Note>>(noteRepository.findAll(),HttpStatus.OK);
}
}
Related
**
2021-11-26 20:30:57.375 WARN 11700 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookRestController': Unsatisfied dependency expressed through field 'bookService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookServiceImpl': Unsatisfied dependency expressed through field 'bookService'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'bookServiceImpl': Requested bean is currently in creation: Is there an unresolvable circular reference?
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 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2021-11-26 20:30:57.393 INFO 11700 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2021-11-26 20:30:57.396 INFO 11700 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2021-11-26 20:30:57.410 INFO 11700 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-11-26 20:30:57.437 ERROR 11700 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter:
**
APPLICATION FAILED TO START
Description:
The dependencies of some of the beans in the application context form a cycle:
bookRestController (field private BookAuthorManyToManyRelationship.service.BookService BookAuthorManyToManyRelationship.Rest.BookRestController.bookService)
┌─────┐
| bookServiceImpl (field private BookAuthorManyToManyRelationship.service.BookService BookAuthorManyToManyRelationship.serviceImpl.BookServiceImpl.bookService)
└─────┘
Action:
Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to 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);
}
}
```
here is cause of your problem
#Service
public class BookServiceImpl implements BookService {
#Autowired
private BookService bookService
I am not able to understand why do you have reference of BookService inside it's own implementation, my best guess you wanted to add BookDAO here.
I'm trying to do a simple CRUD in postgres with spring, but for no reason my IoD mechanism doesn't work and throws an error like this:
Description:
Parameter 0 of constructor in br.com.maptriz.formulario_dinamico.service.FormularioDinamicoService required a bean of type 'br.com.maptriz.formulario_dinamico.repository.FormularioDinamicoRepository' that could not be found.
Action:
Consider defining a bean of type 'br.com.maptriz.formulario_dinamico.repository.FormularioDinamicoRepository' in your configuration.
Here's my code:
FormularioDinamicoApplication.java
package br.com.maptriz.formulario_dinamico;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// #EnableJpaRepositories("br.com.maptriz.formulario_dinamico.repository")
// #EnableScheduling
// #EnableDiscoveryClient
// #ComponentScan
#SpringBootApplication
public class FormularioDinamicoApplication {
public static void main(String[] args) {
SpringApplication.run(FormularioDinamicoApplication.class, args);
}
}
FormularioDinamico
package br.com.maptriz.formulario_dinamico.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "formulario_dinamico")
public class FormularioDinamico {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne
#JoinColumn(name="tipo_tabela")
private Long tabelaId;
private String name;
private String campos;
protected FormularioDinamico() {}
public FormularioDinamico(Long tabelaId, String name, String campos) {
this.tabelaId = tabelaId;
this.name = name;
this.campos = campos;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getTabelaId() {
return this.tabelaId;
}
public void setTabelaId(Long tabelaId) {
this.tabelaId = tabelaId;
}
public String getName() {
return this.name;
}
public void setObservacao(String name) {
this.name = name;
}
public String getCampos() {
return this.campos;
}
public void setCampos(String campos) {
this.campos = campos;
}
#Override
public String toString() {
return "EntidadeGenerica{" +
"id=" + id +
", dataAtualizacao=" + tabelaId +
", dataCadastro=" + name +
", observacao='" + campos + '}';
}
}
FormlarioDinamicoController.java
package br.com.maptriz.formulario_dinamico.controller;
import org.springframework.beans.factory.annotation.Autowired;
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 br.com.maptriz.formulario_dinamico.model.FormularioDinamico;
import br.com.maptriz.formulario_dinamico.service.FormularioDinamicoService;
#RestController
#RequestMapping
public class FormularioDinamicoController {
private final FormularioDinamicoService service;
#Autowired
public FormularioDinamicoController(FormularioDinamicoService service) {
this.service = service;
}
// #GetMapping
// public List<DynamicForm> getDynamicForm() {
// return dynamicFormService.getDynamicForm();
// }
#PostMapping("/create")
public void registrarNovoFormularioDinamico(#RequestBody FormularioDinamico formularioDinamico) {
System.out.println("TEST");
service.adicionarNovoFormularioDinamico(formularioDinamico);
}
}
FormularioDinamicoService.java
package br.com.maptriz.formulario_dinamico.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.maptriz.formulario_dinamico.model.FormularioDinamico;
import br.com.maptriz.formulario_dinamico.repository.FormularioDinamicoRepository;
#Service
public class FormularioDinamicoService {
private final FormularioDinamicoRepository repository;
#Autowired
public FormularioDinamicoService(FormularioDinamicoRepository repository) {
this.repository = repository;
}
// public List<DynamicForm> getDynamicForm() {
// return dynamicFormRepository.findAll();
// }
public void adicionarNovoFormularioDinamico(FormularioDinamico formularioDinamico) {
List<FormularioDinamico> topicos = repository.findAll();
System.out.println("HEREEEE");
System.out.println(topicos);
}
}
And finally FormularioDinamicoRepository.java
package br.com.maptriz.formulario_dinamico.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import br.com.maptriz.formulario_dinamico.model.FormularioDinamico;
public interface FormularioDinamicoRepository
extends JpaRepository<FormularioDinamico, Long> {
List<FormularioDinamico> findAll();
}
My Folder Structure:
src
main
java/br/com/maptriz/formulario_dinamico
controller
model
repository
service
FormularioDinamicoApplication.java
Add #Repository annotation on the interface FormularioDinamicoRepository. It should be working seamlessly.
The moment you add it spring identifies it as a bean and creates an object and injects the bean wherever autowired.
I am new to spring boot and i am writing CRUD operation for basic practices, here is my code.
DemoApplication.java:
package com.example.controller;
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);
}
}
User.java
package com.example.model;
public class User {
String userName;
String password;
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserServices.java:
package com.example.services;
import com.example.model.User;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
#Repository
public interface UserServices {
public String loginService(User user);
}
UserServiceImplementatioin.java:
package com.example.serviceimplementation;
import com.example.model.User;
import com.example.services.UserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class UserServiceImplementation implements UserServices {
public String loginService(User user) {
if(user.getUserName().equals("demouser") && user.getPassword().equals("demopass")) {
return "Login successfully";
}
return "Invalid Username and password";
}
}
ServiceController.java:
package com.example.controller;
import com.example.services.UserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import com.example.model.User;
#RestController
#RequestMapping(value="/askmeanything")
public class ServiceController {
#Autowired
private UserServices userServices;
public UserServices getUserServices() {
return userServices;
}
public void setUserServices(UserServices userServices) {
this.userServices = userServices;
}
#CrossOrigin(origins = "*")
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String getMsg(#RequestBody User user) throws Exception {
return userServices.loginService(user);
}
}
above code giving me the error
Field userServices in com.example.controller.ServiceController required a bean of type 'com.example.services.UserServices' that could not be found.
This is because your DemoApplication is defined in he following package com.example.controller. Thus by default Spring will only scan that package and desendence of it. E.g. com.example.controller.something. It will not scan in parent packages.
Either you move your DemoApplication to the parent package or you have to specify the correct packages for component-scan.
#SpringBootApplication(scanBasePackages={"com.example"})
I suggest to move the class to the parent package and let spring boot do the magic.
My application won't start with the message :
The dependencies of some of the beans in the application context form a cycle:
bookController
↓
bookServiceImpl
┌─────┐
bookCommandToBook
↑ ↓
authorCommandToAuthor
└─────┘
BookController
package pl.springwebapp.webapp.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import pl.springwebapp.webapp.command.BookCommand;
import pl.springwebapp.webapp.service.BookService;
#Slf4j
#Controller
public class BookController {
private BookService bookService;
public BookController(BookService bookService) {
this.bookService = bookService;
}
#RequestMapping("/book/show/{id}")
public String showDescriptionById(#PathVariable long id, Model model){
model.addAttribute("book",bookService.findByID(id));
return "/book/show";
}
#RequestMapping("book/new")
public String newBook(Model model){
model.addAttribute("book", new BookCommand());
return "book/bookform";
}
#PostMapping
#RequestMapping(name = "book")
public String saveOrUpdate(#ModelAttribute BookCommand bookCommand){
bookService.saveBookCommand(bookCommand);
return "redirect:/index";
}
}
BookServiceImpl
package pl.springwebapp.webapp.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import pl.springwebapp.webapp.command.BookCommand;
import pl.springwebapp.webapp.converter.BookCommandToBook;
import pl.springwebapp.webapp.converter.BookToBookCommand;
import pl.springwebapp.webapp.model.Book;
import pl.springwebapp.webapp.repository.BookRepository;
import javax.transaction.Transactional;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
#Slf4j
#Service
public class BookServiceImpl implements BookService {
private BookRepository bookRepository;
private BookCommandToBook bookCommandToBook;
private BookToBookCommand bookToBookCommand;
public BookServiceImpl(BookRepository bookRepository, BookCommandToBook bookCommandToBook, BookToBookCommand bookToBookCommand) {
this.bookRepository = bookRepository;
this.bookCommandToBook = bookCommandToBook;
this.bookToBookCommand = bookToBookCommand;
}
#Override
public Set<Book> getBooks(){
Set<Book> bookSet = new HashSet<>();
bookRepository.findAll().iterator().forEachRemaining(bookSet::add);
return bookSet;
}
#Override
public Book findByID(long id) {
Optional<Book> optionalBook = bookRepository.findById((id));
if(!optionalBook.isPresent()){
throw new RuntimeException("Book not found");
}
return optionalBook.get();
}
#Transactional
#Override
public BookCommand saveBookCommand(BookCommand bookCommand) {
Book receivedBook = bookCommandToBook.convert(bookCommand);
Book savedBook = bookRepository.save(receivedBook);
return bookToBookCommand.convert(savedBook);
}
}
BookCommandToBook
package pl.springwebapp.webapp.converter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import pl.springwebapp.webapp.command.BookCommand;
import pl.springwebapp.webapp.model.Book;
#Component
public class BookCommandToBook implements Converter<BookCommand, Book> {
private AuthorCommandToAuthor authorConverter;
private CategoryCommandToCategory categoryConverter;
public BookCommandToBook(AuthorCommandToAuthor authorConverter, CategoryCommandToCategory categoryConverter) {
this.authorConverter = authorConverter;
this.categoryConverter = categoryConverter;
}
#Override
public Book convert(BookCommand bookCommand) {
Book book = new Book();
book.setId(bookCommand.getId());
book.setTitle(bookCommand.getTitle());
book.setIsbn(bookCommand.getIsbn());
book.setDescription(bookCommand.getDescription());
book.setAuthor(authorConverter.convert(bookCommand.getAuthor()));
if(bookCommand.getCategorySet() != null && bookCommand.getCategorySet().size() > 0 ){
bookCommand.getCategorySet().forEach(categoryCommand -> book.getCategories().add(categoryConverter.convert(categoryCommand)));
}
return book;
}
}
AuthorCommandToAuthor
package pl.springwebapp.webapp.converter;
import lombok.Synchronized;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import pl.springwebapp.webapp.command.AuthorCommand;
import pl.springwebapp.webapp.model.Author;
#Component
public class AuthorCommandToAuthor implements Converter<AuthorCommand, Author> {
private BookCommandToBook bookConverter;
public AuthorCommandToAuthor(BookCommandToBook bookConverter) {
this.bookConverter = bookConverter;
}
#Synchronized
#Override
public Author convert(AuthorCommand authorCommand) {
if(authorCommand==null){
return null;
}
Author author = new Author();
author.setId(authorCommand.getId());
author.setName(authorCommand.getName());
author.setLastName(authorCommand.getLastName());
if(authorCommand.getBookCommandSet() != null && authorCommand.getBookCommandSet().size() > 0){
authorCommand.getBookCommandSet()
.forEach(bookCommand -> author.getBooks().add(bookConverter.convert(bookCommand)));
}
return author;
}
}
AuthorCommand
#Setter
#Getter
#NoArgsConstructor
public class AuthorCommand {
private long id;
private String name;
private String lastName;
private Set<BookCommand> bookCommandSet = new HashSet<>();
}
BookCommand
#Setter
#Getter
#NoArgsConstructor
public class BookCommand {
private long id;
private String title;
private String isbn;
private String description;
private Set<CategoryCommand> categorySet = new HashSet<>();
private AuthorCommand author;
}
Can you help me solve this problem?
You have a cycle in your application context. That means that one bean depends on another and vice versa. Spring will be unable to create those beans, since one bean always has to be created first. More specifically, AuthorCommandToAuthor requires BookCommandToBook and BookCommandToBook requires AuthorCommandToAuthor.
To solve your problem, refactor shared code to a thrid component and inject it into both dependencies. This will eliminate the cycle.
I'm building a rest controller using Spring to handle request and Jackson to serialize data.However I followed tutorial online but I end up getting an error.
HTTP Status 406 -
type Status report
message
description The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.
After Google for a while, I realized that it is because I don't have "application/json" as my "Accept" header in my request:
So I use a tool called Postman to manually add this "Accept" header in the request, send the request again, but still getting the same error:
I'm so confused, I've already included "application/json" as one of accepted data-type, why I still have this data-unsupported error? FYI, here is my Rest Controller class:
package mywebapp.controller;
import java.io.IOException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import mywebapp.dao.model.interfaces.PetDao;
import mywebapp.model.Pet;
#RestController
#RequestMapping(value = "petJson.htm")
public class PetControllerAjax {
private static final Logger LOG = LoggerFactory.getLogger(PetController.class);
public static Logger getLog() {
return LOG;
}
#Autowired
#Qualifier("PetDaoJpaImpl")
private PetDao petDao;
public PetDao getPetDao() {
return petDao;
}
public void setPetDao(PetDao petDao) {
this.petDao = petDao;
}
#RequestMapping(method = RequestMethod.GET)
public List<Pet> getAllPets() throws IOException {
getLog().info("Rest Controller activating........");
List<Pet> petList = getPetDao().getAllPets();
return petList;
}
}
And here is my Pet entity class:
package mywebapp.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Date;
import java.util.Set;
#Entity
#Table(name = "pet")
public class Pet {
private int petId;
private String name;
private String owner;
private String species;
private String sex;
private Date birth;
private Date death;
private Set<Toy> toys;
#Id
#Column(name = "pet_id")
#GeneratedValue
#JsonProperty(value="pet_id",required=true)
public int getId() {
return petId;
}
public void setId(int id) {
this.petId = id;
}
#JsonProperty(value="pet_name",required=true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Date getDeath() {
return death;
}
public void setDeath(Date death) {
this.death = death;
}
#OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER,targetEntity=Toy.class, mappedBy="pet")
public Set<Toy> getToys() {
return toys;
}
public void setToys(Set<Toy> toys) {
this.toys = toys;
}
}
Anyone knows what's going on here? Any hint will be appreciated, lots of thanks in advance!
Jackson 2.7 is not supported by Spring 4.2 - it will be in 4.3+.
Check out the library requirements for Spring on the Spring wiki and see SPR-13728 and SPR-13483.