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

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!

Related

Using transactional in spring boot with hibernate

I am getting the error while using hibernate in spring boot application No qualifying bean of type TransactionManager' available
I am using the following config class:
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#org.springframework.context.annotation.Configuration
#EnableTransactionManagement
public class Config {
#Bean
public SessionFactory sessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
configuration.addAnnotatedClass(Ct.class);
configuration.addAnnotatedClass(St.class);
SessionFactory sessionFactory = configuration.buildSessionFactory();
return sessionFactory;
}
}
#RestController
public class RestAPIController {
#Autowired
private SessionFactory sessionFactory;
#PutMapping("/addS")
#Transactional
public void addSt(#RequestParam("cc") String cc,#RequestParam("st") String st) {
CC cc1= new CC();
CC.setCode(cc);
State state = new State(cc,st);
sessionFactory.getCurrentSession().save(state);
}
}
}
The main reason I added the #Transactional in the addSt method is due to error: The transaction was still an active when an exception occurred during Database.
So I turned to use spring boot for managing transactions. I am not sure what to do here.
--------------------UPDATED CODE--------------------
#Repository
public interface StateRepository extends CrudRepository<State, String> {}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.List;
#Service
#Transactional
public class StateService {
#Autowired
private StateRepository stateRepository;
public void save(State state) {
stateRepository.save(state);
}
public List<State> findAll() {
List<State> states = new ArrayList<>();
stateRepository.findAll().forEach(states::add);
return states;
}
}
For starters use proper layers and write a service and use JPA instead of plain Hibernate. If you want a Session you can always use EntityManager.unwrap to obtain the underlying Session.
#Service
#Transactional
public StateService {
#PersistenceContext
private EntityManager em;
public void save(State state) {
em.persist(state);
}
Use this service in your controller instead of the SessionFactory.
#RestController
public class RestAPIController {
private final StateService stateService;
RestAPIController(StateService stateService) {
this.stateService=stateService;
}
#PutMapping("/addS")
public void addSt(#RequestParam("cc") String cc, #RequestParam("st") String st) {
CC cc1= new CC();
CC.setCode(cc);
State state = new State(cc,st);
stateService.save(state);
}
}
Now ditch your Config class and restart the application.
NOTE
When using Spring Data JPA it is even easier, define a repository extending CrudRepository and inject that into the service instead of an EntityManager. (I'm assuming that Long is the type of primary key you defined).
public interface StateRepository extends CrudRepository<State, Long> {}
#Service
#Transactional
public StateService {
private final StateRepository states;
public StateService(StateRepository states) {
this.states=states;
}
public void save(State state) {
states.save(state);
}
}

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.

java.lang.IllegalArgumentException: Not a managed type: class while initiating repository bean

Hi I am trying to load some database values at start time of spring boot application. I have autowired service, and in service i have autowired Dao. Below is the error.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'validationExpressionService': Unsatisfied dependency expressed through field 'validationExpressionDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IValidationExpressionDao': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.ril.nfg.dao.bean.ValidationExpression
I have added #EnitityScan #EnableJPARepository
FYI, Primary key in the case in String, hope that is ok.
Entity
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* The Class ValidationExpression.
*/
package com.ril.nfg.dao.bean;
#Entity
#Table(name = "VALIDATION_EXPRESSION")
public class ValidationExpression implements Serializable {
private static final long serialVersionUID = 9096950800262493651L;
private String validationId;
private String expression;
private String createdBy;
private Date createdOn;
private String description;
private String responseCode;
#Id
#Column(name = "VALIDATION_ID", nullable = false, length = 100)
public String getValidationId() {
return validationId;
}
public void setValidationId(String validationId) {
this.validationId = validationId;
}
#Column(name = "EXPRESSION", nullable = false, length = 200)
public String getExpression() {
return expression;
}
public void setExpression(String expression) {
this.expression = expression;
}
//remaining getters and setters
}
Repository
package com.ril.nfg.dao.repos;
import com.ril.nfg.dao.bean.ValidationExpression;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* The Interface IValidationExpressionDao.
*/
#Repository
public interface IValidationExpressionDao extends JpaRepository<ValidationExpression, String> {
}
Service
import java.util.List;
#Service
public class ValidationExpressionService {
#Autowired
IValidationExpressionDao validationExpressionDao;
public List<ValidationExpression> getAll() {
return validationExpressionDao.findAll();
}
}
Class with #Autwired Service
public class CacheModuleParam implements ApplicationContextAware{
private static List<ValidationExpression> validationExpressionList = null;
#Autowired
ValidationExpressionService validationExpressionService;
#Override
public void setApplicationContext(final ApplicationContext appContext) throws BeansException {
validationExpressionList = validationExpressionService.getAll();
}
}
Application Class
#ComponentScan(basePackages = {"com.ril.nfg"})
#EnableWebMvc
#EnableAutoConfiguration
#SpringBootApplication//(exclude={DataSourceAutoConfiguration.class})
#EnableJpaRepositories(basePackages="com.ril.nfg.dao.repos",entityManagerFactoryRef="oracleEntityManagerFactory")
//#EntityScan(basePackages = "com.ril.nfg.dao.bean")
public class NFGApplication {
public static void main(String[] args) {
SpringApplication.run(NFGApplication.class, args);
}
}
All solutions on internet focuses on #EntityScan. Please help me understand what is wrong with this code. Thanks in advance
Why do you have all this configuration? Simply put our application in the package tree one level above all the other classes and you can go with a class like this:
#SpringBootApplication
public class NFGApplication {
public static void main(String[] args) {
SpringApplication.run(NFGApplication.class, args);
}
}
Packages:
com.ril.nfg <- here you put NFGApplication
And all other classes in subpackages of com.ril.nfg
And then everything will work!

Unsatisfied dependency expressed through field 'userTokenService'

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.

Spring boot + redis

I am working demo Spring boot application with integration of Redis.
I have referred various site reference but lastly I preferred to follow this: http://www.baeldung.com/spring-data-redis-tutorial
My code is almost same as given in above link. Only change is that I have autowired StudentRepository in my RestController class.
Now when I try to do maven-install at that time it gives me error that
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'studentController': Unsatisfied dependency expressed through field 'studentRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentRepositoryImpl' defined in file [/home/klevu/work/Nimesh/Spring Boot Workspace/bootDemo/target/classes/com/example/demo/redis/repository/StudentRepositoryImpl.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.example.demo.redis.repository.StudentRepositoryImpl]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: No visible constructors in class com.example.demo.redis.repository.StudentRepositoryImpl
When I tried to keep constructor public, it creates build successfully. But I don't know I should do it or not here. I was thinking that rather than Autowiring constructor, I should be able to do setter injection. I also tried below:
#Autowired
private RedisTemplate<String, Student> redisTemplate;
But it is also not working.
package com.example.demo.redis.repository;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import com.example.demo.redis.bean.Student;
#Repository
public class StudentRepositoryImpl implements StudentRepository {
private static final String KEY = "Student";
//#Autowired
private RedisTemplate<String, Student> redisTemplate;
private HashOperations<String, String, Student> hashOps;
#Autowired
private StudentRepositoryImpl(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
#PostConstruct
private void init() {
hashOps = redisTemplate.opsForHash();
}
#Override
public void saveStudent(Student person) {
hashOps.put(KEY, person.getId(), person);
}
#Override
public void updateStudent(Student person) {
hashOps.put(KEY, person.getId(), person);
}
#Override
public Student findStudent(String id) {
return hashOps.get(KEY, id);
}
#Override
public Map<String, Student> findAllStudents() {
return hashOps.entries(KEY);
}
#Override
public void deleteStudent(String id) {
hashOps.delete(KEY, id);
}
}
RedisConfiguration are default and code as below:
package com.example.demo.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
#Configuration
public class RedisConfiguration {
#Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
#Bean
public RedisTemplate<String, Object> redisTemplate(){
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
}
Spring boot main entry point is declared as below:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
#SpringBootApplication
#EnableMongoRepositories(basePackages = {"com.example.demo.mongo.repository"} )
#EnableRedisRepositories(basePackages = {"com.example.demo.redis.repository"})
public class BootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(BootDemoApplication.class, args);
}
}
Demo controller to test redis is as below:
package com.example.demo.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.redis.bean.Student;
import com.example.demo.redis.repository.StudentRepository;
#RestController
#RequestMapping("/student")
public class StudentController {
#Autowired
private StudentRepository studentRepository;
#GetMapping
public ResponseEntity<Map<String, Student>> index() {
Map<String, Student> students = studentRepository.findAllStudents();
return new ResponseEntity<Map<String, Student>>(students, HttpStatus.OK);
}
#RequestMapping(method = RequestMethod.GET, value = "/{id}")
public ResponseEntity<Student> getStudentById(#PathVariable("id") String id) {
Student student = studentRepository.findStudent(id);
return new ResponseEntity<Student>(student, HttpStatus.OK);
}
#RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Student> saveStudent(#RequestBody Student student) {
studentRepository.saveStudent(student);
return new ResponseEntity<Student>(student, HttpStatus.CREATED);
}
#RequestMapping(method = RequestMethod.PUT, value = "/{id}")
public ResponseEntity<Student> updateStudent(#RequestBody Student student) {
studentRepository.updateStudent(student);
return new ResponseEntity<Student>(student, HttpStatus.OK);
}
#RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
public ResponseEntity<Student> deleteMessage(#PathVariable("id") String id) {
studentRepository.deleteStudent(id);
return new ResponseEntity<Student>(HttpStatus.OK);
}
}
You set the constructor as private... change it to public
#Autowired
public StudentRepositoryImpl(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
Change the following redis configuration:
Your original:
#Bean
public RedisTemplate<String, Object> redisTemplate() {
...
}
Change it to:
#Bean
public RedisTemplate<String, ?> redisTemplate(){
...
}
It should work now for you.
You could use Spring Data Redis
Add dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Enable Caching
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
#SpringBootApplication
#EnableCaching
public class RedisDemoApplication {
public static void main(String[] args) {
SpringApplication.run(RedisDemoApplication.class, args);
}
}
Add Cacheable annotation at method to cache in redis
#Cacheable(value = "employee", key = "#id")
public Employee getEmployee(Integer id) {
log.info("Get Employee By Id: {}", id);
Optional<Employee> employeeOptional = employeeRepository.findById(id);
if (!employeeOptional.isPresent()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Id Not foud");
}
return employeeOptional.get();
}

Resources