No qualifying bean of type,expected at least 1 bean which qualifies as autowire, org.springframework.beans.factory.UnsatisfiedDependencyException: - spring-boot

I Created a simple Springboot Application with H2 DB. Not able to start the spring boot Application getting below error on startup. I have added all the necessary configurations.
Exception encountered during context initialization - cancelling
refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'studentController': Unsatisfied
dependency expressed through field 'studentService'; nested exception
is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'com.example.test.serviceimpl.StudentServiceImpl' available: expected
at least 1 bean which qualifies as autowire candidate. Dependency
annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
Controller:
package com.example.test.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.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.example.test.serviceimpl.StudentServiceImpl;
import comm.example.test.model.Student;
#RestController
public class StudentController {
#Autowired(required=true)
private StudentServiceImpl studentService;
#GetMapping("/student")
private List<Student> getAllStudent() {
return studentService.getAllStudent();
}
#GetMapping("/student/{id}")
private Student getStudent(#PathVariable("id") Long id) {
return studentService.getStudentById(id);
}
}
Student Pojo class
package comm.example.test.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
#Getter
#Setter
#AllArgsConstructor
#Entity
#Table(name="student")
public class Student {
#Id
#Column
private Long id;
#Column
private String name;
#Column
private int age;
#Column
private String email;
}
StudentService Interface:
package com.example.test.service;
import java.util.List;
import comm.example.test.model.Student;
public interface StudentService {
List<Student> getAllStudent();
Student getStudentById(Long id);
}
StudentServiceImpl:
package com.example.test.serviceimpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.test.repository.serviceimpl.StudentRepositoryServiceImpl;
import com.example.test.service.StudentService;
import comm.example.test.model.Student;
public class StudentServiceImpl implements StudentService {
#Autowired
private StudentRepositoryServiceImpl serviceImpl;
#Override
public List<Student> getAllStudent() {
return serviceImpl.getAllStudent();
}
#Override
public Student getStudentById(Long id) {
return serviceImpl.getStudentById(id);
}
}
RepositoryService:
package com.example.test.repository.serviceimpl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.test.repository.StudentRepository;
import comm.example.test.model.Student;
#Service
public class StudentRepositoryServiceImpl {
#Autowired
private StudentRepository repo;
public List<Student> getAllStudent() {
List<Student> students = new ArrayList<Student>();
repo.findAll().forEach(student -> students.add(student));
return students;
}
public Student getStudentById(Long id) {
return repo.findById(id).get();
}
}
Repository:
package com.example.test.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import comm.example.test.model.Student;
#Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}

Your StudentServiceImpl needs a #Service annotation to be injected.

Related

Spring Boot issue in join table query in my repository code

Getting unsatisfied dependency error while using #Query in Spring Boot
In my repository I have added query to join tables but getting error at runtime
ERROR:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'empcontroller': Unsatisfied dependency expressed through field 'emprepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepository' defined in com.emp.employeeMangement.api.Repository.EmployeeRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List com.emp.employeeMangement.api.Repository.EmployeeRepository.getJoinInformation(); Reason: Validation failed for query for method public abstract java.util.List com.emp.employeeMangement.api.Repository.EmployeeRepository.getJoinInformation()!; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.emp.employeeMangement.api.Repository.EmployeeRepository.getJoinInformation()!
My code:
package com.emp.employeeMangement.api.Repository;
import com.emp.employeeMangement.api.DTO.ResponseDTO;
import com.emp.employeeMangement.api.Model.Employee;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface EmployeeRepository extends JpaRepository<Employee,Long> {
#Query(value = "SELECT new com.emp.employeeMangement.api.DTO.ResponseDTO(e.empName,e.gender,e.email,e.empCode,a.noOfPresent,a.noOfAbsent) from Employee e JOIN e.Attendence a")
public List<ResponseDTO> getJoinInformation();
}
My controller code:
package com.emp.employeeMangement.api.Controller;
import com.emp.employeeMangement.api.DTO.RequestDTO;
import com.emp.employeeMangement.api.DTO.ResponseDTO;
import com.emp.employeeMangement.api.Exception.ResourceNotFoundException;
import com.emp.employeeMangement.api.Model.Employee;
import com.emp.employeeMangement.api.Repository.AttendenceRepository;
import com.emp.employeeMangement.api.Repository.EmployeeRepository;
import com.emp.employeeMangement.api.Repository.SalaryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
public class Empcontroller {
#Autowired
private EmployeeRepository emprepo;
#Autowired
private AttendenceRepository attrepo;
#Autowired
private SalaryRepository salRepo;
#PostMapping("/saveEmployee")
public Employee saveEmployee(#RequestBody RequestDTO dto){
return emprepo.save(dto.getEmployee());
}
#GetMapping("/findAllEmp")
public List<Employee> findAllEmp(){
return emprepo.findAll();
}
#GetMapping("/getInfo")
public List<ResponseDTO> getJoinInformation(){
return emprepo.getJoinInformation();
}
My response to:
package com.emp.employeeMangement.api.DTO;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
#Data
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class ResponseDTO {
private String empName;
private String email;
private String gender;
private int empCode;
private int noOfPresent;
private int noOfAbsent;
private int salAmount;
}
Spring Data tells you that the query is invalid. After a quick look it seems you are missing the field salAmount in the constructor.

Validate input inside embedded lists using #DecimalMin and #Valid

So what I am trying to do is to create embedded classes with validation in each class and then get the desired error message when I enter an illegal value. When I have embedded classes, validation suddenly stops working for some reason. I have extracted the core of the problem in the classes below
UserController Class:
// UserController.java
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
#RestController
public class UserController {
public void printUsers(#Valid List<User> users) {
System.out.println(users.get(0).getPeople().get(0).getAge());
}
#GetMapping("/")
public void getUser() {
List<User> users = new ArrayList<>();
Person person = new Person();
person.setAge(-10.0);
person.setFirstName("Test");
person.setLastName("Embedded Validation");
List<Person> persons = new ArrayList<>();
persons.add(person);
User user = new User(persons);
users.add(user);
printUsers(users);
}
}
User Class:
// User.java
package com.example.demo;
import lombok.Builder;
import lombok.Data;
import javax.validation.constraints.NotNull;
import java.util.List;
#Data
#Builder
public class User {
#NotNull
private List<Person> people;
}
Person Class:
// Person.java
package com.example.demo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.NotNull;
#Data
#Builder
#AllArgsConstructor
#NoArgsConstructor
public class Person {
#NotNull
#DecimalMin("0.0")
private double age;
#NotNull
private String firstName;
#NotNull
private String lastName;
}
If you run this it will print -10.0, but I have explicitly told the Person class to have a min DecimalVal of 0.0, so my assignment of person.setAge(-10.0); in the UserController class should not be allowed.
How come validation on embedded classes do not work?

APPLICATION FAILED TO START error encountered on SpringBoot

I'm self-studying in Spring boot application and encountered this problem. Weird thing is that I only followed the tutorial but still encountered this
Parameter 0 of constructor in com.example.Project1.service.PersonService required a bean of type 'com.example.Project1.dao.PersonDao' that could not be found.
I have one controller, 2 DAO files, 1 Person for model and 1 for service class.
These are my codes:
PersonController:
package com.example.Project1.api;
import com.example.Project1.model.Person;
import com.example.Project1.service.PersonService;
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;
#RequestMapping("api/v1/person")
#RestController
public class PersonController {
private final PersonService personService;
#Autowired
public PersonController(PersonService personService){
this.personService = personService;
}
#PostMapping
public void addPerson(#RequestBody Person person){
personService.addPerson(person);
}
}
FakePersonDataAccessService
package com.example.Project1.dao;
import com.example.Project1.model.Person;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
#Repository("fakeDao")
public class FakePersonDataAccessService implements PersonDao {
private static List<Person> DB = new ArrayList<>();
#Override
public int insertPerson(UUID id, Person person){
DB.add(new Person(id, person.getName()));
return 1;
}
}
PersonDao
package com.example.Project1.dao;
import com.example.Project1.model.Person;
import java.util.UUID;
public interface PersonDao {
int insertPerson(UUID id, Person person);
default int insertPerson(Person person){
UUID id = UUID.randomUUID();
return insertPerson(id, person);
}
}
Person
package com.example.Project1.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.UUID;
public class Person {
private final UUID id;
private final String name;
public Person(#JsonProperty("id") UUID id, #JsonProperty("name") String name){
this.id = id;
this.name = name;
}
public UUID getId(){
return id;
}
public String getName(){
return name;
}
}
PersonService
package com.example.Project1.service;
import com.example.Project1.dao.PersonDao;
import com.example.Project1.model.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
#Service
public class PersonService {
private final PersonDao personDao;
#Autowired
public PersonService(#Qualifier("mongo") PersonDao personDao){
this.personDao = personDao;
}
public int addPerson(Person person){
return personDao.insertPerson(person);
}
}
I've tried googling the error but found no answer. Hope someone can enlighten me about the error encountered. Thank you~!
You only have "fakeDao" qualifier class that implements PersonDao but your injecting "mongo" qualifier. As another option, you can just removed the #Qualifier annotation in PersonService constructor since you only have one class that implements PersonDao

Encountered error "Consider defining a bean of type 'java.util.concurrent.atomic.AtomicReference' in your configuration"

I am getting the below error while starting spring boot application.
The injection point has the following annotations:
#org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type
'java.util.concurrent.atomic.AtomicReference' in your configuration.
Below is the code .
package de.summer.sampleapplayerv1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#SpringBootApplication(scanBasePackages = {"de.summer.sampleapplayerv1"})
#EnableConfigurationProperties
#EnableJpaRepositories (basePackages ="de.summer.sampleapplayerv1.repository")
#EnableTransactionManagement
public class Sampleapplayerv1Application {
public static void main(String[] args) {
SpringApplication.run(Sampleapplayerv1Application.class, args);
}
}
package de.summer.sampleapplayerv1.service;
import de.summer.sampleapplayerv1.domain.QueueAndPublish;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
#Slf4j
#Service
public class QueueAndPublishServiceImpl implements QueueAndPublishService{
private final AtomicReference<List<QueueAndPublish>> currentJob;
public QueueAndPublishServiceImpl(
#Qualifier("currentJob") AtomicReference<List<QueueAndPublish>> currentJob
){
this.currentJob=currentJob;
}
#Override
public QueueAndPublish getJobStatus(UUID jobId) {
return (QueueAndPublish) currentJob.get().stream()
.filter(j -> j.getJobId()==jobId)
.collect(Collectors.toList());
}
#Override
public List<QueueAndPublish> getAllJobStatus() {
return currentJob.get();
}
#Override
public QueueAndPublish getCategoryDataProcess() {
List<QueueAndPublish> processList=new ArrayList<QueueAndPublish>();
QueueAndPublish process=QueueAndPublish.builder()
.jobId(UUID.randomUUID())
.jobName("Name for Job")
.jobStatus("Not Yet Started")
.build();
Thread t1=new Thread(process.getJobId().toString()){
#Override
public void run(){
log.info("How are you doing");
process.setJobStatus("Completed");
}
};
t1.start();
processList.add(process);
currentJob.set(processList);
return process;
}
#Override
public QueueAndPublish getCatgeoryDataProcessStatus() {
return null;
}
}
package de.summer.sampleapplayerv1.domain;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.Serializable;
import java.util.UUID;
#Getter
#Setter
#Builder
#Entity
public class QueueAndPublish implements Serializable {
#Id
private UUID jobId;
private String jobName;
private String jobStatus;
}
If I remove the constructor, spring boot application is starting up without any errors. If included , start up is failing with unsatisfied dependency errors.
Can someone please help on what is wrong with config?
You expect Spring to create an instance of class QueueAndPublishServiceImpl for the implementation of QueueAndPublishService. This instance needs a constructor parameter of type AtomicReference<List<QueueAndPublish>> injected.
But you obviously do not define any Spring bean (Bean, Component, Service, ...) of that type.
Edit:
public QueueAndPublishServiceImpl(
#Qualifier("currentJob") AtomicReference<List<QueueAndPublish>> currentJob
){
this.currentJob=currentJob;
}
Here you define a constructor parameter to have a AtomicReference<List<QueueAndPublish>>, and even specify it with a #Qualifier. So you need to provide a Spring bean of this class with this qualifier, otherwise Spring cannot inject it into the constructor call.
Consider defining a bean of type 'java.util.concurrent.atomic.AtomicReference' in your configuration.
Means "something like" adding this to your Sampleapplayerv1Application:
#Bean("currentJob") AtomicReference<List<QueueAndPublish>> currentJob() {
// or a list implementation of your choice.
return new AtomicReference<>(new java.util.ArrayList<>());
}

Failed to create query for method public abstract

Simple I want test my application to connect with database to insert
some record statically.
it properly work or not.but it throws this type of error that i
mentioned below;
I donot know where i make mistake,I define everything properly
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'turistRepo': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract com.main.ToursTravels.model.Turist com.main.ToursTravels.repo.TuristRepo.findByName(java.lang.String)! No property name found for type Turist!
turistrepo.java
package com.main.ToursTravels.repo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.main.ToursTravels.model.Turist;
#Repository
public interface TuristRepo extends CrudRepository<Turist, Long> {
Turist findByName(String turistname);
}
vechiletyperepo.java
package com.main.ToursTravels.repo;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.main.ToursTravels.model.Turist;
import com.main.ToursTravels.model.VechileType;
#Repository
public interface VechileTypeRepo extends CrudRepository<VechileType, Long> {
List<VechileType> findByTurist(Turist turist , Sort sort);
}
mainclasss.java
package com.main.ToursTravels;
import java.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.main.ToursTravels.model.Turist;
import com.main.ToursTravels.model.VechileKind;
import com.main.ToursTravels.model.VechileType;
import com.main.ToursTravels.repo.TuristRepo;
import com.main.ToursTravels.repo.VechileTypeRepo;
#SpringBootApplication
public class ToursTravelsApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(ToursTravelsApplication.class, args);
}
#Autowired
TuristRepo trp;
#Autowired
VechileTypeRepo vtrp;
#Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
Turist trs = new Turist();
trs.setTuristname("NewsWels");
trs.setTravelkm(100);
trs.setTraveldate(LocalDate.of(2020, 20, 11));
trs.setDrivername("prabhka5r");
VechileType vtp= new VechileType();
vtp.setVechilekind(VechileKind.SEDAN);
vtp.setRateperkm(6);
vtp.setMinprice(2530.00);
trs.setVechileno("GJ05K2619");
trs.setTotalamount(15186.00);
trs.setBookingstatus(true);
trs.setVechiletype(vtp);
vtp.setTurist(trs);
trp.save(trs);
}
}
turist.java
package com.main.ToursTravels.model;
import java.math.BigDecimal;
import java.time.LocalDate;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import lombok.Data;
#Entity
#Table(name="turist")
#Data
public class Turist {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="truist_id")
private Long truistid;
#Column(name="turistname")
private String turistname;
#Column(name="travel_km")
private int travelkm;
#Column(name="travel_date")
private LocalDate traveldate;
#Column(name="drivername")
private String drivername;
#OneToOne(fetch=FetchType.LAZY,cascade=CascadeType.ALL)
#JoinColumn(name="booking_id")
private VechileType vechiletype;
#Column(name="vechileno")
private String vechileno;
#Column(name="total_amount")
private Double totalamount;
#Column(name="BOOKING_status")
private boolean bookingstatus;
public Turist(){}
public Turist(String turistname, int travelkm, LocalDate traveldate, String drivername, VechileType vechiletype,
String vechileno, Double totalamount, boolean bookingstatus) {
super();
this.turistname = turistname;
this.travelkm = travelkm;
this.traveldate = traveldate;
this.drivername = drivername;
this.vechiletype = vechiletype;
this.vechileno = vechileno;
this.totalamount = totalamount;
this.bookingstatus = bookingstatus;
}
}
VechileType.java
package com.main.ToursTravels.model;
import java.math.BigDecimal;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import lombok.Data;
#Entity
#Table(name="vechiletype")
#Data
public class VechileType {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="booking_id")
private Long bookingid;
#OneToOne(fetch=FetchType.LAZY,cascade=CascadeType.ALL,mappedBy="vechiletype")
private Turist turist;
#Enumerated(EnumType.STRING)
#Column(name="vechilekind")
private VechileKind vechilekind;
#Column(name="rate_per_km")
private int rateperkm;
#Column(name="miniprice")
private Double minprice;
public VechileType(){}
public VechileType(Turist turist, VechileKind vechilekind, int rateperkm, Double minprice) {
this.turist = turist;
this.vechilekind = vechilekind;
this.rateperkm = rateperkm;
this.minprice = minprice;
}
}
Your Repository method references a name field for your Turist class, but none exists. You have turistname available to query.
So your method name should be this:
Turist findByTuristname(String turistname);

Resources