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.
Related
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.
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
I'm using Redis in a spring project and I define a #Component class that uses Redis repository with #Autowire, but when debugging the application, #Component class constructor runs before bean to connect to Redis, therefore the application exits with this error :
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataManager' defined in file [/mnt/D/ms/projects/EventDetection/out/production/classes/ir/rahati/data/datamanager/DataManager.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'ir.rahati.data.messagegraph.redis.RedisMessageGraphRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
DataManager class
#Component
public class DataManager {
private final RedisMessageGraph messageGraph;
#Autowired
public DataManager( RedisMessageGraphRepository redisMessageGraphRepository) {
this.messageGraph=new RedisMessageGraph(redisMessageGraphRepository);
}
}
Redis repository interface
#Repository
public interface RedisMessageGraphRepository extends CrudRepository<MessageGraphModel, String> {
}
Configuration Class
#Configuration
#EnableRedisRepositories("ir.rahati.data.messagegraph")
public class RedisMessageGraphConfig {
#Bean
JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration("localhost", 6379);
redisStandaloneConfiguration.setDatabase(3);
return new JedisConnectionFactory(redisStandaloneConfiguration);
}
#Bean(name = "redis15")
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
}
I Create the bean by configuration with out name
#Configuration
#ConfigurationProperties(prefix = "mysql")
public class DbConfiguration extends BaseDbConfiguration {
#Bean//(name = "fix")
#Override
public DbClient createClient() {
return super.createClient();
}
}
usage:
#Autowired
private DbClient dbClient;
when I running application it can't start up
And throw NoSuchBeanDefinitionException:
No qualifying bean of type [DbClient] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
But I fix it by add name, why??
#Bean(name = "fix")
I also add a test such like this:
public class TestCreate {
#NotNull
private int test;
public Test createTest() {
return new Test(this.test);
}
}
it configuration like this:
#Configuration
#ConfigurationProperties(prefix = "test")
public class TestConfiguration extends TestCreate {
#Override
#Bean
public Test createTest() {
return super.createTest();
}
}
And autowired like this:
#Autowired
private Test test;
However, this test may work well
It also create Bean without name and Autowired with out Qualifier
Please Tell me why....thanks
Sorry.
I have found the results:
Overriding bean definition for bean 'createClient': replacing ...
So Spring-Boot will create Bean by FunctionName rather than returning ObjectName.
I use Java based configuration. When I have had only one UserRepository bean, all was working just fine. But when I added another one implementation of UserRepository, I got this error
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'answerService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.springapp.mvc.service.NewUserService com.springapp.mvc.service.AnswerService.userService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'newUserService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.springapp.mvc.repository.UserRepository com.springapp.mvc.service.NewUserService.userRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.springapp.mvc.repository.UserRepository] is defined: expected single matching bean but found 2: [jpaUserRepository, jsonUserRepository]
Here is my configuration:
#EnableWebMvc
#Configuration
#ComponentScan("com.springapp.mvc")
#PropertySource("classpath:names.properties")
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Bean
public InternalResourceViewResolver setupViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/");
}
}
And my service which is using one of UserService implementation:
#Service
public class NewUserService {
#Autowired
#Qualifier("jsonRepo")
public UserRepository userRepository;
// methods ommited
}
I tried to add #Qualifier annotation to UserRepository userRepository and to specific implementation:
#Repository("jsonRepo")
public class JsonUserRepository implements UserRepository {...}
But it doesn't work.
How can I fix this problem?
Try this:
#Repository
#Qualifier("jsonRepo")
public class JsonUserRepository implements UserRepository {...}