Unsatisfied dependency expressed through field 'userTokenService' - spring

homeControler
package com.book.controller;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.book.entity.User;
import com.book.entity.security.UserToken;
import com.book.entity.security.service.SecurityService;
import com.book.entity.security.service.UserTokenService;
#Controller
public class HomeController {
#Autowired
private UserTokenService userTokenService;
#Autowired
private SecurityService securityService;
#RequestMapping("/")
public String getHome() {
return "index";
}
#RequestMapping("/myaccount")
public String myAccount() {
return "myAccount";
}
#RequestMapping("/login")
public String login(Model model) {
model.addAttribute("classActiveLogin", true);
return "myAccount";
}
#RequestMapping("/forgetPassword")
public String forgetPassword(Model model) {
model.addAttribute("classActiveForgetPassword", true);
return "myAccount";
}
#RequestMapping("/newUser")
public String newUser(Locale locale, #RequestParam("token") String token, Model model) {
UserToken userToken = userTokenService.getPasswordResetToken(token);
if (userToken == null) {
String msg = "Invalid Token";
model.addAttribute("msg", msg);
return "redirect:/badRequest";
}
User user = userToken.getUser();
String username = user.getUsername();
UserDetails userDetails = securityService.loadUserByUsername(username);
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(),
userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
model.addAttribute("classActiveEdit", true);
return "myProfile";
}
}
User Token
package com.book.entity.security;
import java.util.Calendar;
import java.util.Date;
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 com.book.entity.User;
#Entity
public class UserToken {
private static final int EXPIRATION = 60 * 24;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String token;
#OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)
#JoinColumn(nullable=false, name="user_id")
private User user;
private Date expiryDate;
public UserToken(final String token, final User user) {
super ();
this.token = token;
this.user = user;
this.expiryDate = calculateExpiryDate(EXPIRATION);
}
private Date calculateExpiryDate (final int expiryTimeInMinutes) {
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(new Date().getTime());
cal.add(Calendar.MINUTE, expiryTimeInMinutes);
return new Date(cal.getTime().getTime());
}
public void updateToken(final String token) {
this.token = token;
this.expiryDate = calculateExpiryDate(EXPIRATION);
}
#Override
public String toString() {
return "P_Token [id=" + id + ", token=" + token + ", user=" + user + ", expiryDate=" + expiryDate + "]";
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Date getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(Date expiryDate) {
this.expiryDate = expiryDate;
}
public static int getExpiration() {
return EXPIRATION;
}
}
UserTokenService
package com.book.entity.security.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.book.entity.User;
import com.book.entity.security.UserToken;
import com.book.entity.security.repo.PasswordResetRepo;
import com.book.entity.security.repo.UserTokenRepo;
#Service("userTokenService")
public class UserTokenService implements UserTokenRepo{
#Autowired
private PasswordResetRepo repo;
#Override
public UserToken getPasswordResetToken(final String token) {
return repo.findByToken(token);
}
#Override
public void createPasswordResetTokenForUser(final User user, final String token) {
final UserToken myToken = new UserToken(token, user);
repo.save(myToken);
}
}
UserTokenRepo
package com.book.entity.security.repo;
import com.book.entity.User;
import com.book.entity.security.UserToken;
public interface UserTokenRepo {
UserToken getPasswordResetToken(final String token);
void createPasswordResetTokenForUser(final User user, final String token);
}
SecurityService
package com.book.entity.security.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.book.entity.User;
import com.book.entity.security.repo.SecurityUserRepository;
#Service
public class SecurityService implements UserDetailsService {
#Autowired
private SecurityUserRepository securityUserRepository;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = securityUserRepository.findByUsername(username);
if (null == user) {
throw new UsernameNotFoundException("Username not found");
}
return user;
}
}
PasswordResetRepo
package com.book.entity.security.repo;
import java.util.Date;
import java.util.stream.Stream;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import com.book.entity.User;
import com.book.entity.security.UserToken;
public interface PasswordResetRepo extends JpaRepository<UserToken, Long > {
UserToken findByToken(String token);
UserToken findByUser(User user);
Stream<UserToken> findAllByExpiryDateLessThan(Date now);
#Modifying
#Query("delete from P_Token t where t.expirydate <= ?1")
void deleteAllExpiredSince(Date now);
}
Error:-->
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'userTokenService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userTokenService': Unsatisfied dependency expressed through field 'repo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'passwordResetRepo': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: antlr/RecognitionException

May be problem lays on HomeController bellow code:
#Autowired
private UserTokenService userTokenService;
Replace this code with bellow code:
#Autowired
private UserTokenRepo userTokenService;
Your main error portion is:
Unsatisfied dependency expressed through field 'repo'; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'passwordResetRepo': Invocation of init
method failed; nested exception is java.lang.NoClassDefFoundError:
antlr/RecognitionException
Here it is failed to create bean passwordResetRepo cause antlr/RecognitionException
Its solution is java.lang.ClassNotFoundException: antlr.RecognitionException shows antlr lib missing.
Add it and itss done :)
You can try to add the following dependency. It will solve your issue.
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr-complete</artifactId>
<version>3.5.2</version>
</dependency>
Another possible consideration:
Please check all JPA query on PasswordResetRepo repository. Sometimes if query not matched with entity variable name then Spring can't create bean for that repository
Hope this will solve your problem.
Thanks :)

Take a look at the stacktrace. The issue is: spring IoC container is failing to create homeController bean; because the container is failing to create userTokenService bean; and that is because the container is failing to create passwordResetRepo bean with java.lang.NoClassDefFoundError.
Adding the following in your config file should solve your problem:
<jpa:repositories base-package="com.book.entity.security.repo" />
As you are using Spring Boot, please check this guide on Accessing Data with JPA.
From the above mentioned guide:
By default, Spring Boot will enable JPA repository support and look
in the package (and its subpackages) where #SpringBootApplication is
located. If your configuration has JPA repository interface
definitions located in a package not visible, you can point out
alternate packages using #EnableJpaRepositories and its type-safe
basePackageClasses=MyRepository.class parameter.

Related

Spring boot application failed to start with exception org.springframework.beans.factory.NoSuchBeanDefinitionException:

I am using spring boot v2.5.2. Below is my folder structure and code. This is simple test project.
My folder structure:
RESTController Class:
package com.user.UserManagementSystem.controller;
import com.user.UserManagementSystem.model.User;
import com.user.UserManagementSystem.service.UserServiceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/api/v1/")
public class UserController {
#Autowired
private UserServiceImpl userRepository;
#GetMapping("/getAllUsers")
public List<User> getAllUsers() {
return userRepository.getUsers();
}
#GetMapping("/")
public String home() {
return "Hello";
}
}
User.java
package com.user.UserManagementSystem.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name= "Users")
public class User {
public User() {
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name ="userName")
private String userName;
#Column(name ="name")
private String name;
#Column(name ="language")
private String language;
#Column(name ="mobileNumber")
private int mobileNumber;
public User(String userName, String name, String language, int mobileNumber) {
this.userName = userName;
this.name = name;
this.language = language;
this.mobileNumber = mobileNumber;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public int getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(int mobileNumber) {
this.mobileNumber = mobileNumber;
}
}
UserRepository.java
package com.user.UserManagementSystem.repository;
import com.user.UserManagementSystem.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends JpaRepository<User, Long>{
}
UserService.java
package com.user.UserManagementSystem.service;
import com.user.UserManagementSystem.model.User;
import java.util.List;
public interface UserService {
List<User> getUsers();
User getUserById(Long id);
User addUser(User user);
void deleteUser(Long id);
}
UserServiceImpl.java
package com.user.UserManagementSystem.service;
import com.user.UserManagementSystem.repository.UserRepository;
import com.user.UserManagementSystem.model.User;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class UserServiceImpl implements UserService{
#Autowired
UserRepository userRepository;
#Override
public List<User> getUsers() {
return userRepository.findAll();
}
#Override
public User getUserById(Long id) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public User addUser(User user) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void deleteUser(Long id) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
UserManangmentSystemApplication.java
package com.user.UserManangmentSystem;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication(scanBasePackages = {"com.user.UserManangmentSystem", "com.user.UserManagementSystem.controller", "com.user.UserManagementSystem.repository", "com.user.UserManagementSystem.service"})
//#SpringBootApplication
public class UserManangmentSystemApplication {
public static void main(String[] args) {
SpringApplication.run(UserManangmentSystemApplication.class, args);
}
}
application.properties:
spring.datasource.url=jdbc:mariadb://localhost:3306/ums
spring.datasource.username=ums
spring.datasource.password=ums
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDB53Dialect
server.port=8888
debug=true
When it build the project i am getting :
Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.user.UserManagementSystem.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1790) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1346) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:657) ~[spring-beans-5.3.8.jar:5.3.8]
Thanks in Advance.
Typo in your base package name which makes packages different.
Change
com.user.UserManangmentSystem
To
com.user.UserManangementSystem
Correct management spelling.
You have correct package structure it will collect all bean within base package and sub package also. No need explicitly mention package scan. If you have any spell mistakes then that error will occur.

No qualifying bean of type 'testgroup.private_clinic.dao.PatientDAO' available in SpringBoot Application

I'm developing crud application, and experiencing difficulties with springboot, which fails on startup. This is what i got:
20764 WARNING [main] --- org.springframework.context.annotation.AnnotationConfigApplicationContext: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'patientServiceImpl': Unsatisfied dependency expressed through method 'setPatientDAO' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'testgroup.private_clinic.dao.PatientDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Screenshot of project structure:
Model:
package testgroup.private_clinic.model;
import javax.persistence.*;
#Entity
#Table(name="Patients")
public class Patient {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
int id;
#Column(name="patient_name")
String name;
#Column(name = "patient_surname")
String surname;
#Column(name = "patient_patronimic")
String patronimic;
#Column(name="adress")
String adress;
#Column(name = "status")
String status;
#Column(name="diagnosis")
String diagnosis;
//+getters and setters
Controller:
package testgroup.private_clinic.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import testgroup.private_clinic.model.Patient;
import testgroup.private_clinic.service.PatientService;
import java.util.List;
#RestController
public class PatientController {
PatientService patientService;
#Autowired
public void setPatientService(PatientService patientService){
this.patientService = patientService;
}
#RequestMapping(method = RequestMethod.GET)
public ModelAndView allPatients(){
List<Patient> patients = patientService.allPatients();
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("patients");
modelAndView.addObject("patientList", patients);
return modelAndView;
}
#RequestMapping(value= "/edit{id}", method = RequestMethod.GET)
public ModelAndView editPage(#PathVariable("id") int id){
Patient patient = patientService.getByID(id);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("editPage");
modelAndView.addObject("patient", patient);
return modelAndView;
}
#RequestMapping(value="/edit", method = RequestMethod.POST)
public ModelAndView editPatient(#ModelAttribute("patient") Patient patient){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("redirect:/");
patientService.edit(patient);
return modelAndView;
}
}
Repository:
package testgroup.private_clinic.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import testgroup.private_clinic.model.Patient;
import javax.transaction.Transactional;
import java.util.*;
#Repository
public class PatientDAOImpl implements PatientDAO {
SessionFactory sessionFactory;
#Autowired
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
#Override
#Transactional
public List<Patient> allPatients() {
Session session = sessionFactory.getCurrentSession();
return session.createQuery("from Patient").list();
}
#Override
#Transactional
public void add(Patient patient) {
Session session = sessionFactory.getCurrentSession();
session.persist(patient);
}
#Override
#Transactional
public void delete(Patient patient) {
Session session = sessionFactory.getCurrentSession();
session.delete(patient);
}
#Override
#Transactional
public void edit(Patient patient) {
Session session = sessionFactory.getCurrentSession();
session.update(patient);
}
#Override
#Transactional
public Patient getByID(int id) {
Session session = sessionFactory.getCurrentSession();
return session.get(Patient.class, id);
}
}
Service:
package testgroup.private_clinic.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import testgroup.private_clinic.model.Patient;
import testgroup.private_clinic.dao.PatientDAO;
import javax.transaction.Transactional;
import java.util.List;
#Service
public class PatientServiceImpl implements PatientService{
PatientDAO patientDAO;
#Autowired
public void setPatientDAO(PatientDAO patientDAO){
this.patientDAO = patientDAO;
}
#Transactional
#Override
public List<Patient> allPatients() {
return patientDAO.allPatients();
}
#Transactional
#Override
public void add(Patient patient) {
patientDAO.add(patient);
}
#Transactional
#Override
public void delete(Patient patient) {
patientDAO.delete(patient);
}
#Transactional
#Override
public void edit(Patient patient) {
patientDAO.edit(patient);
}
#Transactional
#Override
public Patient getByID(int id) {
return patientDAO.getByID(id);
}
}
Main class:
package testgroup.private_clinic.service;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootClass {
public static void main(String[] args){
SpringApplication.run(testgroup.private_clinic.service.SpringBootClass.class, args);
}
}
Spring Boot uses classpath component scanning meaning, your entry-point class which is SpringBootClass will scan for all beans within its class path unless you configure it not to.
Looking into your project structure, SpringBootClass is under the testgroup.private_clinic.service package thus Spring Boot will only scan this package for beans and it only found the PatientServiceImpl however, before it injects this to the application context, it will need to inject first its dependency PatientDAO which is not part of the testgroup.private_clinic.service package thus, explains your error.
You have two options to fix this:
Move your SpringBootClass to the base package testgroup.private_clinic - this will make Spring Boot scan on all you components under this package and its sub-packages (e.g., service, dao)
Use #ComponentScan on your SpringBootClass and define there the base package you want to scan for beans.
#ComponentScan(basePackages = "testgroup.private_clinic")
Thanks and cheers!

Creating role requirement for accessig a webpage with Spring BOOT

I am trying to add to website I created a requirement for user to be logged-in in order to access content and also split 3 types of users: non logged-in person, admin and standard user. I struggle a lot with it as I was unable to find a guide that would both explain it to me and work properly at the same time. Could you guys please help me and tell em what am I doing wrong? I spent 6 days trying to get this logging in feature to work and I feel compleatly lost at this point because I tried so many different codes and approaches from guides I found. As for my database I am using SQL Workbench.
The problem is (at least I think this is the problem) that in SecurityConfig in configure method I am not actually passing Role of the User (hasAnyRole('Admin')). I was trying to do it in many ways but I don't really udnerstand how am I supposed to pass Role to it.
Here is my controller package:
MainController:
package Projekt.ProjektAI.controller;
import Projekt.ProjektAI.entities.Book;
import Projekt.ProjektAI.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import java.security.Provider;
import java.util.List;
#Controller
public class MainController {
private BookService service;
#Autowired
public MainController(BookService service){
this.service = service;
}
#RequestMapping("/")
public String viewNormalHomePage(Model model) {
List<Book> listBooks = service.listAll();
model.addAttribute("listBooks", listBooks);
return "indexNormal";
}
#RequestMapping("/admin")
public String viewAdminHomePage(Model model) {
List<Book> listBooks = service.listAll();
model.addAttribute("listBooks", listBooks);
return "index";
}
#RequestMapping("/user")
public String viewUserHomePage(Model model) {
List<Book> listBooks = service.listAll();
model.addAttribute("listBooks", listBooks);
return "indexStandard";
}
#RequestMapping("/admin/new")
public String showNewBookPage(Model model) {
Book book = new Book();
model.addAttribute("book", book);
return "newBook";
}
#RequestMapping("/admin/edit/{id}")
public ModelAndView showEditBookPage(#PathVariable(name = "id") Long id) {
ModelAndView mav = new ModelAndView("editBook");
Book book = service.get(id);
mav.addObject("book", book);
return mav;
}
#RequestMapping(value = "/admin/save", method = RequestMethod.POST)
public String saveBook(#ModelAttribute("book") Book book) {
service.save(book);
return "redirect:/";
}
#RequestMapping("/admin/delete/{id}")
public String deleteBook(#PathVariable(name = "id") Long id) {
service.delete(id);
return "redirect:/";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model) {
return "login";
}
#RequestMapping(value = "/user", method = RequestMethod.GET)
public String userIndex() {
return "user/index";
}
}
UserRegistrationController:
package Projekt.ProjektAI.controller;
import javax.validation.Valid;
import Projekt.ProjektAI.service.UserService;
import Projekt.ProjektAI.registrationDTO.UserRegistrationDTO;
import Projekt.ProjektAI.entities.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping("/registration")
public class UserRegistrationController {
#Autowired
private UserService userService;
#ModelAttribute("user")
public UserRegistrationDTO userRegistrationDto() {
return new UserRegistrationDTO();
}
#GetMapping
public String showRegistrationForm(Model model) {
return "registration";
}
#PostMapping
public String registerUserAccount(#ModelAttribute("user") #Valid UserRegistrationDTO userDto,
BindingResult result) {
User existing = userService.findByEmail(userDto.getEmail());
if (existing != null) {
result.rejectValue("email", null, "There is already an account registered with that email");
}
if (result.hasErrors()) {
return "registration";
}
userService.save(userDto);
return "redirect:/registration?success";
}
}
Entities package:
Book entity:
package Projekt.ProjektAI.entities;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
#Entity
#Getter
#Setter
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column
private String autor;
#Column
private String tytul;
#Column
private String gatunek;
#Column
private float cena;
public Book() {
}
#Override
public String toString() {
return "Book{" +
"id=" + id +
", autor='" + autor + '\'' +
", tytul='" + tytul + '\'' +
", gatunek='" + gatunek + '\'' +
", cena=" + cena +
'}';
}
}
Role entity:
package Projekt.ProjektAI.entities;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
#Getter
#Setter
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
protected Role() {}
public Role(String name) {
this.name = name;
}
#Override
public String toString() {
return "Role{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
User entity:
package Projekt.ProjektAI.entities;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.util.Collection;
#Entity
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#Table(uniqueConstraints = #UniqueConstraint(columnNames = "email"))
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String email;
private String password;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(
name = "users_roles",
joinColumns = #JoinColumn(
name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(
name = "role_id", referencedColumnName = "id"))
private Collection <Projekt.ProjektAI.entities.Role> roles;
public Collection <Projekt.ProjektAI.entities.Role> getRoles() {
return roles;
}
public void setRoles(Collection <Projekt.ProjektAI.entities.Role> roles) {
this.roles = roles;
}
#Override
public String toString() {
return "User{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", password='" + "*********" + '\'' +
", roles=" + roles +
'}';
}
}
registration DTO package:
FieldMatch interface:
package Projekt.ProjektAI.registrationDTO;
import javax.validation.Payload;
import javax.validation.Constraint;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
#Target({
TYPE,
ANNOTATION_TYPE
})
#Retention(RUNTIME)
#Constraint(validatedBy = FieldMatchValidator.class)
#Documented
public #interface FieldMatch {
String message() default "{constraints.field-match}";
Class < ? > [] groups() default {};
Class < ? extends Payload > [] payload() default {};
String first();
String second();
#Target({
TYPE,
ANNOTATION_TYPE
})
#Retention(RUNTIME)
#Documented
#interface List {
FieldMatch[] value();
}
}
Field Match Validator:
package Projekt.ProjektAI.registrationDTO;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.apache.commons.beanutils.BeanUtils;
public class FieldMatchValidator implements ConstraintValidator <Projekt.ProjektAI.registrationDTO.FieldMatch, Object > {
private String firstFieldName;
private String secondFieldName;
#Override
public void initialize(final Projekt.ProjektAI.registrationDTO.FieldMatch constraintAnnotation) {
firstFieldName = constraintAnnotation.first();
secondFieldName = constraintAnnotation.second();
}
#Override
public boolean isValid(final Object value, final ConstraintValidatorContext context) {
try {
final Object firstObj = BeanUtils.getProperty(value, firstFieldName);
final Object secondObj = BeanUtils.getProperty(value, secondFieldName);
return firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
} catch (final Exception ignore) {}
return true;
}
}
User Registration DTO:
package Projekt.ProjektAI.registrationDTO;
import lombok.Getter;
import lombok.Setter;
import javax.validation.Valid;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
#Projekt.ProjektAI.registrationDTO.FieldMatch.List({
#Projekt.ProjektAI.registrationDTO.FieldMatch(first = "password", second = "confirmPassword", message = "The password fields must match"),
#Projekt.ProjektAI.registrationDTO.FieldMatch(first = "email", second = "confirmEmail", message = "The email fields must match")
})
#Getter
#Setter
public class UserRegistrationDTO {
#NotEmpty
private String firstName;
#NotEmpty
private String lastName;
#NotEmpty
private String password;
#NotEmpty
private String confirmPassword;
#Email
#NotEmpty
private String email;
#Email
#NotEmpty
private String confirmEmail;
#AssertTrue
private Boolean terms;
}
repositories package:
Book Repository
package Projekt.ProjektAI.repositories;
import Projekt.ProjektAI.entities.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface BookRepository extends JpaRepository<Book, Long> {
}
User Repository:
package Projekt.ProjektAI.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import Projekt.ProjektAI.entities.User;
#Repository
public interface UserRepository extends JpaRepository < User, Long > {
User findByEmail(String email);
}
security package:
package Projekt.ProjektAI.security;
import Projekt.ProjektAI.entities.User;
import Projekt.ProjektAI.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import Projekt.ProjektAI.service.UserService;
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserService userService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/new", "/edit/{id}", "/save", "/delete/{id}")
.access("hasAnyRole('Admin')")
.and()
.authorizeRequests()
.antMatchers("/registration**","/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login?logout")
.permitAll();
}
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
auth.setUserDetailsService(userService);
auth.setPasswordEncoder(passwordEncoder());
return auth;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
}
service package:
Book Service:
package Projekt.ProjektAI.service;
import Projekt.ProjektAI.entities.Book;
import Projekt.ProjektAI.repositories.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class BookService {
private BookRepository repo;
#Autowired
public BookService(BookRepository repo)
{
this.repo =repo;
}
public List<Book> listAll() {
return repo.findAll();
}
public void save(Book book) {
repo.save(book);
}
public Book get(long id) {
return repo.findById(id).get();
}
public void delete(long id) {
repo.deleteById(id);
}
}
User Service interface:
package Projekt.ProjektAI.service;
import Projekt.ProjektAI.registrationDTO.UserRegistrationDTO;
import Projekt.ProjektAI.entities.User;
import org.springframework.security.core.userdetails.UserDetailsService;
public interface UserService extends UserDetailsService {
User findByEmail(String email);
User save(UserRegistrationDTO registration);
}
User Service Implementation:
package Projekt.ProjektAI.service;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import Projekt.ProjektAI.service.UserService;
import Projekt.ProjektAI.registrationDTO.UserRegistrationDTO;
import Projekt.ProjektAI.entities.User;
import Projekt.ProjektAI.entities.Role;
import Projekt.ProjektAI.service.UserService;
import Projekt.ProjektAI.registrationDTO.UserRegistrationDTO;
import Projekt.ProjektAI.repositories.UserRepository;
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserRepository userRepository;
#Autowired
private BCryptPasswordEncoder passwordEncoder;
public User findByEmail(String email) {
return userRepository.findByEmail(email);
}
public User save(UserRegistrationDTO registration) {
User user = new User();
user.setFirstName(registration.getFirstName());
user.setLastName(registration.getLastName());
user.setEmail(registration.getEmail());
user.setPassword(passwordEncoder.encode(registration.getPassword()));
user.setRoles(Arrays.asList(new Role("ROLE_USER")));
return userRepository.save(user);
}
#Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user = userRepository.findByEmail(email);
if (user == null) {
throw new UsernameNotFoundException("Invalid username or password.");
}
return new org.springframework.security.core.userdetails.User(user.getEmail(),
user.getPassword(),
mapRolesToAuthorities(user.getRoles()));
}
private Collection < ? extends GrantedAuthority > mapRolesToAuthorities(Collection < Role > roles) {
return roles.stream()
.map(role -> new SimpleGrantedAuthority(role.getName()))
.collect(Collectors.toList());
}
}
application properties:
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.datasource.url=jdbc:mysql://localhost:3366/projektai?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=admin
Thank you very much for any tips!

What other possible issues could there be to getting my spring project running?

I am trying to start my spring project and am getting the following error:
Error starting Tomcat context. Exception:
org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating
bean with name 'jwtRequestFilter': Unsatisfied dependency expressed through field
'userService'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with
name 'userService': Unsatisfied dependency expressed through field 'userRepository'; nested
exception is org.springframework.beans.factory.BeanCreationException: Error creating bean
with name 'userRepository': Cannot create inner bean '(inner bean)#cf199f9' of type
[org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property
'entityManager'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'(inner bean)#cf199f9': Cannot resolve reference to bean 'entityManagerFactory' while
setting constructor argument; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'entityManagerFactory' defined in class path resource
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation
of init method failed; nested exception is org.hibernate.service.spi.ServiceException:
Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
userRepository:
package com.plearnit.website.config;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.plearnit.website.services.UserService;
import io.jsonwebtoken.ExpiredJwtException;
#Component
public class JwtRequestFilter extends OncePerRequestFilter {
#Autowired
private UserService userService;
#Autowired
private JwtTokenUtil jwtTokenUtil;
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain)
throws ServletException, IOException {
final String requestTokenHeader = request.getHeader("Authorization");
String username = null;
String jwtToken = null;
// JWT Token is in the form "Bearer token". Remove Bearer word and get
// only the Token
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
jwtToken = requestTokenHeader.substring(7);
try {
username = jwtTokenUtil.getUsernameFromToken(jwtToken);
} catch (IllegalArgumentException e) {
System.out.println("Unable to get JWT Token");
} catch (ExpiredJwtException e) {
System.out.println("JWT Token has expired");
}
} else {
logger.warn("JWT Token does not begin with Bearer String");
}
// Once we get the token validate it.
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null)
{
UserDetails userDetails = userService.loadUserByUsername(username);
// if token is valid configure Spring Security to manually set
// authentication
if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new
UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
// After setting the Authentication in the context, we specify
// that the current user is authenticated. So it passes the
// Spring Security Configurations successfully.
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
chain.doFilter(request, response);
}
}
UserService:
package com.plearnit.website.services;
import java.util.ArrayList;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import com.plearnit.website.models.User;
import com.plearnit.website.config.JwtTokenUtil;
import com.plearnit.website.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
#Service
public class UserService implements UserDetailsService {
#Autowired
private UserRepository userRepository;
#Autowired
private PasswordEncoder bcryptEncoder;
#Autowired
private JwtTokenUtil jwtTokenUtil;
#Autowired
private HttpServletRequest request;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found with username: " + username);
}
return new org.springframework.security.core.userdetails.User(user.getUsername(),
user.getPassword(),
new ArrayList<>());
}
public User save(User user) {
user.setPassword(bcryptEncoder.encode(user.getPassword()));
return userRepository.save(user);
}
public User loadCurrentUser(){
String token = request.getHeader("Authorization").replace("Bearer ", "");
return userRepository.findByUsername(jwtTokenUtil.getUsernameFromToken(token));
}
public Optional<User> findById (Integer id) {
return userRepository.findById(id);
}
}
UserRepository:
package com.plearnit.website.repositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.plearnit.website.models.User;
#Repository
public interface UserRepository extends CrudRepository<User, Integer> {
User findByUsername(String username);
}
User:
package com.plearnit.website.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.util.Date;
import javax.persistence.*;
#Entity
#Table(name = "user")
#Data
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column
private String username;
#Column
#JsonIgnore
private String password;
#Column(updatable=false)
private Date createdAt;
private Date updatedAt;
#PrePersist
protected void onCreate(){
this.createdAt = new Date();
}
#PreUpdate
protected void onUpdate(){
this.updatedAt = new Date();
}
}
Related dependencies:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Things I've tried:
Make sure MySQL is running
Confirmed MySQL Credentials
Compared my files against my Github repository (no changes)
Made sure dependencies were included in pom.xml
Added Lombok #NoArgsConstructor to user model
Searched SO for 2 hours
Seems it might be something outside my project, but I cannot figure out what else could be the issue.
Where else can I look for a source to this error beyond where I've looked so far?
Update -
Turns out I wasn't scrolling up enough on the errors to see there was a complaint related to the timezone on the DB. Not sure why, but all of a sudden, after months of working, that the timezone needed to be specified in the DB initialization string.
If I am not mistaken, Entity should have a separate empty constructor. And one more constructor with data, which comes from request.

No qualifying bean of type 'com.springmvc.dao.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate

I am getting an error as No qualifying bean of type 'com.springmvc.dao.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate. for the following code, My base class is "com.springmvc"
My Controller Class is
package com.springmvc.controller;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
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.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.springmvc.dao.UserDAO;
import com.springmvc.dao.UserDAOImpl;
import com.springmvc.type.User;
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#Autowired
private UserDAO usrdao;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("Date", formattedDate );
return "index";
}
/*
#RequestMapping(value="/login",method = RequestMethod.POST)
public String welcome(Locale locale,Model model,#ModelAttribute("LoginBean")LoginBean login){
if(login != null && login.getUserName() != "" && login.getPassword() != ""){
if(login.getUserName().equals("ajith") && login.getPassword().equals("123")){
model.addAttribute("msg","Welcome "+login.getUserName());
return "welcome";
}
else{
model.addAttribute("error","Invalid Login Details");
return "index";
}
}
else{
model.addAttribute("error","Please Enter Login Details");
return "index";
}
}
*/
#RequestMapping(value="/checkLogin",method = RequestMethod.POST)
public String CheckUser(Model model,#ModelAttribute("User")User user){
if(user != null && user.getUserName() != "" && user.getPass() != ""){
boolean isActive = usrdao.isActiveUser(user.getUserName(), user.getPass());
if(isActive){
List<User> usrLst = usrdao.ListAllUsers();
model.addAttribute("message",user.getUserName());
model.addAttribute("usrLst",usrLst);
return "home";
}
else{
model.addAttribute("error","Invalid Login Details");
return "index";
}
}
return "index";
}
#RequestMapping(value="/createUser", method = RequestMethod.GET)
public String RedirectCreateUser(Model model){
return "createUser";
}
public String createUser(Model model, #ModelAttribute User user){
usrdao.CreateOrUpdateUser(user);
return "";
}
}
UserDAO
package com.springmvc.dao;
import java.util.List;
import com.springmvc.type.User;
public interface UserDAO {
public void CreateOrUpdateUser(User user);
public void DeleteUser(int uid);
public User GetUser(int uid);
public List<User> ListAllUsers();
public boolean isActiveUser(String userName,String pass);
}
UserDAOImpl
package com.springmvc.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Repository;
import com.springmvc.type.User;
#Repository("UserDAO")
public class UserDAOImpl implements UserDAO {
private JdbcTemplate jdbc;
/*
public void setJdbc(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
*/
public UserDAOImpl(DataSource DS) {
jdbc = new JdbcTemplate(DS);
}
#Override
public void CreateOrUpdateUser(User user) {
if(user.getUid() == 0){
String query = "INSERT INTO userdetails(UserName,Name,Pass) VALUES(?,?,?)";
jdbc.update(query,user.getUserName(),user.getName(),user.getPass());
}
else{
String query = "UPDATE userdetails SET UserName = ?,Name = ?,Pass = ?,isActive = ? WHERE id = ?";
jdbc.update(query, user.getUserName(),user.getName(),user.getPass(),user.getIsActive(),user.getUid());
}
}
#Override
public void DeleteUser(int uid) {
String query = "DELETE FROM userdetails WHERE id = ?";
jdbc.update(query, uid);
}
#Override
public User GetUser(int uid) {
String query = "SELECT * FROM userdetails WHERE id = ?";
return jdbc.query(query, new ResultSetExtractor<User>() {
#Override
public User extractData(ResultSet rs) throws SQLException, DataAccessException {
if(rs.next()){
User user = new User();
user.setUid(rs.getInt("id"));
user.setUserName(rs.getString("UserName"));
user.setName(rs.getString("Name"));
user.setIsActive(rs.getInt("isActive"));
return user;
}
return null;
}
});
}
#Override
public List<User> ListAllUsers() {
String query = "SELECT * FROM userdetails";
List <User> usrLst = jdbc.query(query, new RowMapper<User>() {
#Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setUid(rs.getInt("id"));
user.setUserName(rs.getString("UserName"));
user.setName(rs.getString("Name"));
user.setIsActive(rs.getInt("isActive"));
return user;
}
});
return usrLst;
}
#Override
public boolean isActiveUser(String userName, String pass) {
String query = "SELECT id FROM userdetails WHERE UserName = ? AND Pass = ? AND isActive = 1";
SqlRowSet rs = jdbc.queryForRowSet(query,userName,pass);
if(rs.next())
return true;
else
return false;
}
}
Thank You
UserDAOImpl do not have default constructor. either add default constructor or autowire the construction arg.
Spring is using a strong naming convention.
Try to use as a variable userDao as the autowired variable and use the same string in the #repository.
See this little explanation here:
https://www.tutorialspoint.com/spring/spring_beans_autowiring.htm

Resources