Unsatisfied dependency in spring - java

I want to implement JPA repositories as mentioned here. I think my problem is I want to use some functions from the JPA Repository itself and I #Autorwired it But I'm not completely sure
Error Message:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'addBothStudentsHandler': Unsatisfied dependency expressed through method 'setMajorRepository' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'majorRepository' defined in io.asiam.tansiq.repositories.MajorRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot create inner bean '(inner bean)#78f146b5' of type [org.springframework.data.repository.core.support.RepositoryFragmentsFactoryBean] while setting bean property 'repositoryFragments'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#78f146b5': Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customMajorRepositoryImplFragment': Cannot resolve reference to bean 'customMajorRepositoryImpl' while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customMajorRepositoryImpl': Unsatisfied dependency expressed through field 'majorRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'majorRepository': FactoryBean threw exception on object creation; nested exception is java.lang.NullPointerException
What I have tried so far:
1- tried to use setter-based #Autowired instead of field-based (But no change)
2- tried to use #Lazy also nothing changed
**Code: **
CustomMajorRepository.java
public interface CustomMajorRepository {
void addStudentToMajor(Student student, Major major);
void increaseMajorLimit(UUID majorId, int amount);
}
CustomMajorRepositoryImpl.java
private MajorRepository majorRepository;
public MajorRepository getMajorRepository() {
return majorRepository;
}
#Autowired
public void setMajorRepository(MajorRepository majorRepository) {
this.majorRepository = majorRepository;
}
// rest of implementation details
MajorRepository.java
#Lazy
public interface MajorRepository extends JpaRepository<Major, UUID>, CustomMajorRepository {
}

I think you should use dependency injection via constructor or setter, for example:
private MajorRepository majorRepository;
public CostumMajorRepositoryImpl(MajorRepository mh) {
this.majorRepository = mh;
}
Here is the spring.io article about the setter and constructor injection:
https://spring.io/blog/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/

Related

circular reference between Spring Security and org.springdoc.ui.SwaggerConfig when upgrading to Spring Boot 2.6

When upgrading my application from Spring Boot 2.5 to 2.6, I am getting this error :
Error creating bean with name 'securityConfig': Unsatisfied dependency
expressed through method 'setContentNegotationStrategy' parameter 0;
nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name
'org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration':
Unsatisfied dependency expressed through method 'setConfigurers'
parameter 0;
nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'org.springdoc.ui.SwaggerConfig':
Unsatisfied dependency expressed through field
'swaggerIndexTransformer';
nested exception is
org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'org.springdoc.ui.SwaggerConfig':
Requested bean is currently in creation: Is there an unresolvable
circular reference?
This error is documented on https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.6-Release-Notes#circular-references-prohibited-by-default and I know I could "fix" it by setting a property and go back to Spring Boot 2.5 behavior.. But if I can take the opportunity to fix a circular reference, I may as well do it for the future.
My securityConfig is simple, because my application is a public application returning some html content, to all callers, with no authentication. so this is my config :
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity security) throws Exception {
//application is open to everyone - no security
security.httpBasic().disable();
}
}
the setContentNegotationStrategy that the error mentions is a method from WebSecurityConfigurerAdapter that I am not overriding, so I am not able to understand what I need to do.
if I delete my SecurityConfig class, then I still have an error, same as before but without the mention of my SecurityConfig class:
Error creating bean with name
'org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration':
Unsatisfied dependency expressed through method 'setConfigurers'
parameter 0;
nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'org.springdoc.ui.SwaggerConfig':
Unsatisfied dependency expressed through field
'swaggerIndexTransformer';
nested exception is
org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'org.springdoc.ui.SwaggerConfig':
Requested bean is currently in creation: Is there an unresolvable
circular reference?
what is the recommended way to deal with what seems to be a circular reference between Spring Security and org.springdoc.ui.SwaggerConfig ?
The problem's caused by org.springdoc.ui.SwaggerConfig. It has been fixed by these changes which are available in springdocs-openapi 1.5.13.

Error creating bean; Unsatisfied dependency expressed through field

I have a central library for certain functions and now I have trouble integrating that library.
The library is written in spring boot and contains a class: com.common.Security.
It is defined like this:
package com.common;
....
#Service
#EnableConfigurationProperties(SecurityProperties.class)
#Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class Security {
....
}
I try to use this in another class:
package org.special;
import com.common.Security;
#Configuration
public class WebServiceConfig {
#Autowired
private Security security;
....
}
But I get some errors:
Error creating bean with name 'myController': Unsatisfied dependency expressed through field 'WebServiceclient';
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'webserviceClient':
Unsatisfied dependency expressed through field 'template'; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'webServiceTemplate' defined in class path resource [org/special/WebServiceConfig.class]:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.ws.client.core.WebServiceTemplate]: Factory method 'webServiceTemplate' threw exception;
nested exception is org.springframework.beans.factory.BeanCreationException:
nested exception is org.springframework.beans.factory.support.ScopeNotActiveException: Error creating bean with name 'scopedTarget.Security': Scope 'request' is not active for the current thread;
consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found:
What can I do to fix this?
Removing the Scope was quite helpfull.
I tried this before but some of my tests failed after that. I didn't see, that this was because of missing settings in application.yaml for the tests.
They were not neccessary when scope is request.

Custom Query Spring Data JPA

I need a custom Query in my Repository which extends CrudRepository
#Repository
public interface SongListRepository extends CrudRepository<SongList, Integer> {
#Query("SELECT sl FROM song_list sl WHERE sl.owner=:owner")
Set<SongList> findAllSongListsForUser(
#Param("owner") String owner);
}
When I try to start the following excpetion is thrown:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'songListController': Unsatisfied dependency expressed through field 'songListService';
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'songListService': Unsatisfied dependency expressed through field 'repository';
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'songListRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.Set htwb.ai.songsservice.repository.SongListRepository.findAllSongListsForUser(java.lang.String)!
How do i create custom Querys in a CrudRepository?
You don't need to create your own query. Simply use the auto generate query based on the method signature.
List<SongList> findAllByOwner(String owner);
This will create the query.

BasicDataSource is overridden by non-compatible bean instance of type UrlDecodingDataSource

I tried to expose my Spring Restful web api to Pivotal Cloud Foundary, I successfully connected with Pivotal MySql database, in Local it is working fine but when I push the war in PCF it throws an exception
nested exception is java.lang.IllegalStateException: #Bean method
SpringBeanContainer.dataSource called as bean reference for type
[org.apache.commons.dbcp2.BasicDataSource] but overridden by non-compatible
bean instance of type [org.cloudfoundry.reconfiguration.org.springframework.cloud.service.relational.UrlDecodingDataSource].
I am new to cloud and i don't have an idea much about it, it seems that UrlDecodingDataSource tries to override something, due to this my sessionFactory is not able to create as bean.
Detailed Log
[OUT] org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'loginController': Unsatisfied dependency
expressed through field 'userDetailService'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'userDetailService': Unsatisfied dependency
expressed through field 'uddDao'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'userDetailDaoImpl': Unsatisfied dependency expressed
through field 'sessionFactory'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean
with name 'sessionFactory' defined in
com.javarnd.cc.configuration.SpringBeanContainer: Bean instantiation via
factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to instantiate
[org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method
'sessionFactory' threw exception; nested exception is
java.lang.IllegalStateException: #Bean method SpringBeanContainer.dataSource
called as bean reference for type [org.apache.commons.dbcp2.BasicDataSource]
but overridden by non-compatible bean instance of type [org.cloudfoundry.reconfiguration.org.springframework.cloud.service.relational.UrlDecodingDataSource].
DataSource snippet in my SpringBeanContainer
#Bean // Simple Bean Defination in XML
public BasicDataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty(DRIVER_CLASS));
dataSource.setUrl(env.getProperty(URL));
dataSource.setUsername(env.getProperty(USERNAME));
dataSource.setPassword(env.getProperty(PASSWORD));
return dataSource;
}
Kindly help me to resolve this or sugge

Failed to determine a suitable driver class

when starting the application, see the below error:
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'blockDataController': Injection of resource dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'blockSummaryImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'prodCodeMapper' defined in file [D:\YueNiuProject\StockMarket\yueniu-stock-data\market-data-dao\target\classes\com\yueniu\stock\market\data\mapper\block\ProdCodeMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory';
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception;
nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
the connection with a sql database, you must configure datasource in application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://..
spring.datasource.username=//..
spring.datasource.password=//..
if you dont need to config the datasource, you can use the exclude . like this:
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
it would not register the DataSource with default configuration, then passed the issue for throw Exception
sometimes if you bean configuration in same package it won't work. Like the properties loading bean need to be in separate package. Not sure this answer will be accepted or not , for me it worked after moving below code into different package.
#Bean
public PlatformTransactionManager oracleTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(oracleEntityManager().getObject());
return transactionManager;
}

Categories

Resources