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;
}
}
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 have an Amazon Lambda (springboot) that is deployed and works fine.
I inject services from external projects (dependency add to pom) this way:
#Bean
public SomeExternalService someExternalService() {
return new SomeExternalService;
}
I have to do this because when uploaded to Amazon, #Autowired doesn't work.
Now, from another springboot project (not lambda) I have this service that uses a DAO.
Service
#Service
public class StateService {
#Autowired
private StateRepository repository;
/**
* Find all {#code State}
*/
public void findSomething(String thing) {
return repository.findSomething("thing");
}
.....
Repository
#EnableScan
public interface StateRepository extends PagingAndSortingRepository<State, String> {
List<State> findSomething(String thing);
When building I get
Error creating bean with name 'StateService': Unsatisfied dependency
expressed through field 'repository'
and
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'mypackage.repository.StateRepository'
available: expected at least 1 bean which qualifies as autowire
candidate.
I inject that service exactly like the others
#Bean
public StateService stateService() {
return new StateService;
}
I can't do the same for StateRepository.
StateRepository class must have #Component annotation or add it in your #Configuration class as #Bean.
#Configuration
#ComponentScan("com.company")
public class ConfigClass {
// your #Bean's
#Bean
public StateRepository stateRepository() {
return new StateRepository();
}
// now can #Autowired
}
I'm migrating from spring-data-neo4j version 4.1 to 4.2.
On the application startup I'm getting an error:
Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.neo4j.ogm.session.Session' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
repository.ActivityRecordRepository.java:
public interface ActivityRecordRepository extends GraphRepository<ActivityRecord>, ActivityRecordRepositoryCustom {}
repository.ActivityRecordRepositoryCustom.java:
public interface ActivityRecordRepositoryCustom {
...
}
repository.impl.ActivityRecordRepositoryImpl.java:
public class ActivityRecordRepositoryImpl implements ActivityRecordRepositoryCustom {
private final Session session;
public ActivityRecordRepositoryImpl(Session session) {
this.session = session;
}
....
}
My configuration:
#ComponentScan
#Configuration
#EnableNeo4jRepositories("com.example.repository")
#EnableTransactionManagement
public class ApplicationConfiguration {
....
#Bean
public EventListener eventListener() {
return new CustomEventListener();
}
#Bean
public SessionFactory getSessionFactory() {
final SessionFactory sessionFactory = new SessionFactory(databaseConfiguration, "com.example.entity");
sessionFactory.register(eventListener());
return sessionFactory;
}
}
How to properly autowire session object to custom repository implementation?
I'm using:
Spring Version: 4.3.2.RELEASE
Spring Data Neo4j Version: 4.2.11.RELEASE
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 {...}