below code is working fine but if i comment the jdbcTemplateRandomName method in OracleConfiguration class i get the below error : -
I am trying to understand why i am getting the error by commenting jdbcTemplateRandomName method
Error is in BaseDaoImpl class.
Exception in thread "main"
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'baseDaoImpl': Unsatisfied dependency
expressed through field 'jdbcTemplate'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'org.springframework.jdbc.core.JdbcTemplate'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'org.springframework.jdbc.core.JdbcTemplate'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
#Component
public class BaseDaoImpl {
#Autowired
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
#Configuration
public class OracleConfiguration {
#Bean
DataSource dataSource() throws SQLException {
OracleDataSource dataSource = new OracleDataSource();
//removed code for brevity setting username,password to datasource
return dataSource;
}
#Bean
public JdbcTemplate jdbcTemplateRandomName(DataSource dataSource) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.setResultsMapCaseInsensitive(true);
return jdbcTemplate;
}
public class RolesDaoImpl extends BaseDaoImpl implements RolesDao {
//removed lot of unnecessary code for the question
List<Roles> rolesList = getJdbcTemplate().query(sql,
new BeanPropertyRowMapper<Roles>(Roles.class));
If you comment jdbcTemplateRandomName() method you will remove declaration of JdbcTemplate bean from your Spring IoC configuration. So Spring will not be able to find suitable object to populate jdbcTemplate property of your BaseDaoImpl class
Related
I have this funny error, I say it is funny because my project was working and it just crashed.
I believe I have implemented everything I was supposed to implement to achieve the multi data source.
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'quoteController' defined in file [C:\Users\S4\Desktop\S4Projects\wirk-devserv-intranet\source\back-end\target\classes\com\api\controllers\QuoteController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'quoteServiceImpl' defined in file [C:\Users\S4\Desktop\S4Projects\wirk-devserv-intranet\source\back-end\target\classes\com\api\services\implementation\QuoteServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.api.repository.customer.CustomerRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Description:
Parameter 1 of constructor in com.api.services.implementation.QuoteServiceImpl required a bean of type 'com.api.repository.customer.CustomerRepository' that could not be found.
Action:
Consider defining a bean of type 'com.api.repository.customer.CustomerRepository' in your configuration.
#Autowired
private final CustomerRepository customerRepository;
#Autowired
private final QuoteRepository quoteRepository;
#Component
public interface CustomerRepository extends JpaRepository<Customer,
Integer> {
}
Config File
#EnableJpaRepositories(
basePackageClasses = {
QuoteRepository.class,
CustomerConfig.class
},
entityManagerFactoryRef = "quoteEntityManager",
transactionManagerRef = "quoteTransactionManager")
public class QuoteConfig {
#Bean(name = "quoteEntityManager")
#Primary
public LocalContainerEntityManagerFactoryBean quoteEntityManager(EntityManagerFactoryBuilder builder, #Qualifier("quoteDataSource") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages(Quote.class)
.persistenceUnit("S4DevservIntranet")
.build();
}
#Primary
#Bean("quoteDataSource")
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource quoteDataSource() {
return DataSourceBuilder.create().build();
}
#Primary
#Bean("quoteTransactionManager")
public PlatformTransactionManager quoteTransactionManager(#Qualifier("quoteEntityManager") LocalContainerEntityManagerFactoryBean quoteEntityManager) {
return new JpaTransactionManager(Objects.requireNonNull(quoteEntityManager.getObject()));
}
}
You don't need to use #Component annotation since you use the spring-data JpaRepository interface. but if you wouldn't you have to use #Repository annotation.
In this part you add CustomerConfig class instead CustomerRepository in the list of JpaRepositories
#EnableJpaRepositories(
basePackageClasses = {
QuoteRepository.class,
CustomerConfig.class
},
It must be:
#EnableJpaRepositories(
basePackageClasses = {
QuoteRepository.class,
CustomerRepository.class
},
Error Message tells it everything, seems you haven't created bean for CustomerRepository, so annotate the class with #Repository or #Component.
I'm trying to test the findByPhoneNumber method in this repository
public interface UserRepository extends ReactiveMongoRepository<User, String> {
Mono<User> findByPhoneNumber(String phoneNumber);
}
ATM, my test looks like this
#ExtendWith(SpringExtension.class)
class UserRepositoryTest {
#Autowired
private UserRepository repository;
#Test
void findByPhoneNumber() {
val phoneNumber = "11111 111111";
val user = repository.save(User.builder().phoneNumber(phoneNumber).password("password").build());
assertEquals(user, repository.findByPhoneNumber(phoneNumber));
}
}
When I run it, I get this error
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'io.freesale.repository.UserRepositoryTest': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'io.freesale.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I'm a Spring noob so please don’t bully me too hard 😀
I was missing the #DataMongoTest annotation
main Class:
package *.*.*;
#SpringBootApplication
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class, args);
}
}
DBUtils.java
package *.*.*.dataaccess.dbutils;
#Service
public class DBUtils {
#Autowired
UserRepository userRepository;
public UserEntity getUserEntityById(String id) {
return userRepository.findById(id);
}
}
Repository Class:
package *.*.*.dataaccess.repository;
#Repository
public interface UserRepository extends JpaRepository<UserEntity, UserIdentity> {
UserEntity findById(String id);
}
and also UserEntity java class is in package *.*.*.dataaccess.dao;
Test Class:
#SpringBootTest
class UserApplicationTests {
#Autowired
DBUtils utils; // issue is with this
#Test
void contextLoads() {
}
}
While doing maven test for entire project and getting the below error:
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'DBUtils': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '...dataaccess.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '...dataaccess.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I have used #Service on DBUtils and #Repository on JpaRepository but still getting the above error and using springboot is 2.4.1.
Can anyone please help here?
In application.yml I defined datasource:
spring:
datasource:
driver-class-name: ru.yandex.clickhouse.ClickHouseDriver
username: default
url: jdbc:clickhouse://localhost:8123/default
I too create some config:
#Configuration
#AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MyConfig {
#Getter
private ReportRoutingDataSource dataSourceStorage = new ReportRoutingDataSource();
#Bean("dataSourceStorage")
public DataSource dataSource(#Qualifier("dataSource") DataSource dataSource) {
dataSourceStorage.setDefaultTargetDataSource(dataSource);
dataSourceStorage.setTargetDataSources(resolvedDataSources());
dataSourceStorage.afterPropertiesSet();
return dataSourceStorage;
}
#Bean
public Map<Object, Object> resolvedDataSources() {
//some another logic;
}
}
ReportRoutingDataSource:
public class ReportRoutingDataSource extends AbstractRoutingDataSource {
#Override
protected Object determineCurrentLookupKey() {
return RequestContext.getKeyToChoseDataSource();
}
}
I want use auto-configuration to create a default datasource from a yml file and add it to dataSourceStorage.setDefaultTargetDataSource(dataSource) as default datasource.
I set annotation #AutoConfigureAfter(DataSourceAutoConfiguration.class), that my config is created after autoconfiguration of the standard datasource.
But, whent I start my app, I have error:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataSourceStorage' defined in class path resource [com/example/spring/MyConfig.class]: Unsatisfied dependency expressed through method 'dataSource' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Qualifier(value=dataSource)}
But, why? How can I fix it?
Replace your 'dataSource' method with
#Bean("dataSourceStorage")
public ReportRoutingDataSource reportRoutingDataSource (#Autowired("dataSource") DataSource dataSource) {
ReportRoutingDataSource dataSourceStorage = new ReportRoutingDataSource();
dataSourceStorage.setDefaultTargetDataSource(dataSource);
dataSourceStorage.setTargetDataSources(resolvedDataSources());
dataSourceStorage.afterPropertiesSet();
return dataSourceStorage;
}
and get rid of the #Getter for ReportRoutingDataSource.
#Configuration
public class MyConfig {
#Bean
public Foobar foobar(#Value("${my.value}") String v) {
return new Foobar(v);
}
}
#Component
public class MyComp {
private final Foobar foobar;
public MyComp(Foobar foobar) {
this.foobar = foobar;
System.out.println(foobar);
}
}
If my.value is not set, I will get this error message
java.lang.IllegalArgumentException: Could not resolve placeholder 'my.value' in string value "${my.value}"
Now my.value is also secured by #ConditionalOnProperty("my.value")
#Configuration
public class MyConfig {
#ConditionalOnProperty("my.value")
#Bean
public Foobar foobar(#Value("${my.value}") String v) {
return new Foobar(v);
}
}
If my.value is not set, I will get this error message
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myComp' defined in file [/home/stephan/workspaces/workspace_mercateo/demo/target/classes/com/example/MyComp.class]: Unsatisfied dependency expressed through constructor parameter 0: No qualifying bean of type [com.example.Foobar] found for dependency [com.example.Foobar]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.Foobar] found for dependency [com.example.Foobar]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
[...]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.Foobar] found for dependency [com.example.Foobar]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
Though spring recognizes that my.value is missing there is nothing about this in the output log.
Is there a way to configure spring so that
1) #Conditional is used
and
2) error message contains "my.value is missing"
?