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.
Related
I am trying to fetch data from a table in MySQL using JpaRepository.
I am geeting an error by running code like -
Error creating bean with name 'chassiscontroller': Unsatisfied dependency expressed through field 'service': Error creating bean with name 'chassisserviceimpl': Unsatisfied dependency expressed through field 'dao': Error creating bean with name 'chassisdao' defined in com.ChassisInfo.chassis.dao.chassisdao defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class com.ChassisInfo.model.chassismodel.
Controller
package com.ChassisInfo.chassis.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ChassisInfo.chassis.model.ChassisModel;
import com.ChassisInfo.chassis.service.ChassisService;
#RestController
public class ChassisController {
#Autowired
private ChassisService service;
#GetMapping("/chnum")
public List<ChassisModel> getchassisnumberinfo(){
return service.getAll();
}
}
Service-
package com.ChassisInfo.chassis.service;
import java.util.List;
import com.ChassisInfo.chassis.model.ChassisModel;
public interface ChassisService{
List<ChassisModel> getAll();
}
ServiceImpl-
package com.ChassisInfo.chassis.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ChassisInfo.chassis.dao.ChassisDao;
import com.ChassisInfo.chassis.model.ChassisModel;
#Service
#lombok.AllArgsConstructor
#lombok.NoArgsConstructor
public class ChassisServiceimpl implements ChassisService {
#Autowired
private ChassisDao dao;
#Override
public List<ChassisModel> getAll() {
// TODO Auto-generated method stub
return dao.findAll();
}
Dao-
package com.ChassisInfo.chassis.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.stereotype.Repository;
import com.ChassisInfo.chassis.model.ChassisModel;
#Repository
#EnableJpaRepositories
public interface ChassisDao extends JpaRepository<ChassisModel,String> {
#Query(value = "Select * from chassis_master" ,nativeQuery = true)
List<ChassisModel> findAll();
}
Model-
package com.ChassisInfo.model;
public class chassismodel {
private String vin;
private String active;
private String chassisNumber;
private String chassisSeries;
private String statusChangedTime;
private String tag;
private String truckid;
private String id;
private String chassis_number;
private String chassis_series;
private String status_changed_time;
private String truck_id;
public String getVin() {
return vin;
}
public void setVin(String vin) {
this.vin = vin;
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public String getChassisSeries() {
return chassisSeries;
}
public void setChassisSeries(String chassisSeries) {
this.chassisSeries = chassisSeries;
}
public String getStatusChangedTime() {
return statusChangedTime;
}
public void setStatusChangedTime(String statusChangedTime) {
this.statusChangedTime = statusChangedTime;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getTruckid() {
return truckid;
}
public void setTruckid(String truckid) {
this.truckid = truckid;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getChassis_number() {
return chassis_number;
}
public void setChassis_number(String chassis_number) {
this.chassis_number = chassis_number;
}
public String getChassis_series() {
return chassis_series;
}
public void setChassis_series(String chassis_series) {
this.chassis_series = chassis_series;
}
public String getStatus_changed_time() {
return status_changed_time;
}
public void setStatus_changed_time(String status_changed_time) {
this.status_changed_time = status_changed_time;
}
public String getTruck_id() {
return truck_id;
}
public void setTruck_id(String truck_id) {
this.truck_id = truck_id;
}
public String getChassisNumber() {
return chassisNumber;
}
public void setChassisNumber(String chassisNumber) {
this.chassisNumber = chassisNumber;
}
}
ChassisApplication-
package com.ChassisInfo.chassis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.ChassisInfo.chassis.controller.ChassisController;
#SpringBootApplication
#EnableJpaRepositories
public class ChassisApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(ChassisApplication.class, args);
ChassisController chassisController = context.getBean(ChassisController.class);
chassisController.getchassisnumberinfo();
}
}
Try to use #RequiredArgsConstructor (lombok) in chassisserviceimpl, since dao field is not accessible for autowiring. Also add final for the field:
private final chassisdao dao;
This is probably because you are missing the #EnableJpaRepositories(basePackages = "your.package.name") in you #SpringBootApplication
This is the Annotation to enable JPA repositories. Will scan the package of the annotated configuration class for Spring Data repositories by default.
I am getting the below error when trying to run the Spring Boot app.
*************************** APPLICATION FAILED TO START
Description:
Field repository in com.javanovice.crud.example.service.ProductService
required a bean of type
'com.javanovice.crud.example.repository.ProductRepository' that could
not be found.
The injection point has the following annotations:
#org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type
'com.javanovice.crud.example.repository.ProductRepository' in your
configuration.
ProductRepository.java
package com.javanovice.crud.example.repository;
import com.javanovice.crud.example.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface ProductRepository extends JpaRepository<Product,Integer> {
Product findByName(String name);
}
ProductService.java
package com.javanovice.crud.example.service;
import com.javanovice.crud.example.entity.Product;
import com.javanovice.crud.example.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class ProductService {
#Autowired
private ProductRepository repository;
public Product saveProduct(Product product) {
return repository.save(product);
}
public List<Product> saveProducts(List<Product> products) {
return repository.saveAll(products);
}
public List<Product> getProducts() {
return repository.findAll();
}
public Product getProductById(int id) {
return repository.findById(id).orElse(null);
}
public Product getProductByName(String name) {
return repository.findByName(name);
}
public String deleteProduct(int id) {
repository.deleteById(id);
return "product removed !! " + id;
}
public Product updateProduct(Product product) {
Product existingProduct = repository.findById(product.getId()).orElse(null);
existingProduct.setName(product.getName());
existingProduct.setQuantity(product.getQuantity());
existingProduct.setPrice(product.getPrice());
return repository.save(existingProduct);
}
}
ProductController.java
package com.javanovice.crud.example.controller;
import com.javanovice.crud.example.entity.Product;
import com.javanovice.crud.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
public class ProductController {
#Autowired
private ProductService service;
#PostMapping("/addProduct")
public Product addProduct(#RequestBody Product product) {
return service.saveProduct(product);
}
#PostMapping("/addProducts")
public List<Product> addProducts(#RequestBody List<Product> products) {
return service.saveProducts(products);
}
#GetMapping("/products")
public List<Product> findAllProducts() {
return service.getProducts();
}
#GetMapping("/productById/{id}")
public Product findProductById(#PathVariable int id) {
return service.getProductById(id);
}
#GetMapping("/product/{name}")
public Product findProductByName(#PathVariable String name) {
return service.getProductByName(name);
}
#PutMapping("/update")
public Product updateProduct(#RequestBody Product product) {
return service.updateProduct(product);
}
#DeleteMapping("/delete/{id}")
public String deleteProduct(#PathVariable int id) {
return service.deleteProduct(id);
}
}
SpringBootCrudExampleApplication.java
package com.javanovice.crud.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
public class SpringBootCrudExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootCrudExampleApplication.class, args);
}
}
You need to remove exclude = {DataSourceAutoConfiguration.class } as follows:
#SpringBootApplication
public class SpringBootCrudExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootCrudExampleApplication.class, args);
}
}
Otherwise, autoconfiguration will not kick in for Persistence related beans, including the Repositories.
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.
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);
}
}
I got this error in Userservice.java file
'inferred type 'S' for type parameter 'S' is not within its bound;'
I don't know what is talking about and where I should change..
please check my file and give me some advice
enter image description here
package com.therealdanvega.service;
import com.therealdanvega.domain.User;
import com.therealdanvega.repository.UserRepository;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class UserService {
private UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public Iterable<User> list() {
return userRepository.findAll();
}
public User save(User user) {
return userRepository.save(user);
}
public void save(List<User> users) {
userRepository.save(users);
}
}
User
package com.therealdanvega.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import javax.persistence.*;
#Data
#AllArgsConstructor
#Entity
public class User {
#Id
#GeneratedValue( strategy = GenerationType.AUTO )
private Long id;
private String name;
private String username;
private String email;
private String phone;
private String website;
#Embedded
private Address address;
#Embedded
private Company company;
public User() {}
}
UserController
package com.therealdanvega.controller;
import com.therealdanvega.domain.User;
import com.therealdanvega.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/users")
public class UserController {
private UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
#GetMapping("/list")
public Iterable < User > list() {
return userService.list();
}
}
JsondbApplication
package com.therealdanvega;
import com.fasterxml.jackson.core.type.TypeReference;
import com.therealdanvega.domain.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.therealdanvega.service.UserService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
#SpringBootApplication
public class JsondbApplication {
public static void main(String[] args) {
SpringApplication.run(JsondbApplication.class, args);
}
#Bean
CommandLineRunner runner(UserService userService){
return args -> {
// read JSON and load json
ObjectMapper mapper = new ObjectMapper();
TypeReference<List<User>> typeReference = new TypeReference<List<User>>(){};
InputStream inputStream = TypeReference.class.getResourceAsStream("/json/users.json");
try {
List<User> users = mapper.readValue(inputStream,typeReference);
userService.save(users);
System.out.println("Users Saved!");
} catch (IOException e){
System.out.println("Unable to save users: " + e.getMessage());
}
};
}
}
UserRepository
package com.therealdanvega.repository;
import com.therealdanvega.domain.User;
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<User,Long> {
}
In class UserService in save(List users) method userRepository.save(users) throw error Inferred type 'S' for type parameter 'S' is not within its bound; should extend 'com.therealdanvega.domain.User'
I faced similar issue and by using repository.saveAll() method, it resolved.