Spring NoSuchBeanDefinitionException when wiring a #Component with value defined - spring

My component is defined as below
#Component("myBo")
public class MyBO {
#Autowired
JpaRepository<MyData, Long> repository;
Spring Data Interface:
public interface MyDataRepository extends JpaRepository<MyData, Long> {
Entitymanager definition:
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory( EntityManagerFactoryBuilder builder, #Qualifier("dmDs") final DataSource dmDs) {
LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = builder.dataSource(dmDs).packages(new String[]{"my.packages"}).build();
return localContainerEntityManagerFactoryBean;
}
and my test fails with this error
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myBO': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.jpa.repository.JpaRepository<MyData, java.lang.Long>' 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.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.jpa.repository.JpaRepository<MyData, java.lang.Long>' available: expected at least 1 bean which qualifies as autowire candidate.
whereas the following works fine. Need help in understanding this behavior.
#Component
public class MyBO {
#Autowired
JpaRepository<MyData, Long> repository;
Thanks

You should not autowire JpaRepository<MyData, Long> as is. You should extend it and create your own interface as follows.
public interface MyRepository extends JpaRepository<MyData, Long> {
}
The reason you won't be able to autowire JpaRepository directly is because it is annotated with NoRepositoryBean annotation and that prevents creating an instance of it. It is always recommended to extend the base repo classes and create your own interfaces.
P.S: Do not forget to enable Jpa Repositories on these repo interfaces you are going to create. Otherwise you won't be able to autowire them.
Similar to this in your xml config.
<jpa:repositories base-package="com.acme.repositories"/>

Related

NoBean found exception

**I am getting below error even though i have down the #autowired .please some one let me know why this issue happening its a ant build with spring config
utor.
2022-07-08 10:18:09,856 WARN org.springframework.context.support.
ClassPathXmlApplicationContext - Exception encountered during context initialization
cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'delegateProcessor':
Unsatisfied dependency expressed through field 'headerProcessor';
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean found for dependency
[org.springframework.batch.item.ItemProcessor<com.abc.proj.model.FileHeader,
com.abc.proj.model.FileHeader>]:
expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true),
#org.springframework.beans.factory.annotation.Qualifier(value=headerProcessor)}
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'delegateProcessor': Unsatisfied dependency expressed
through field 'headerProcessor';
nested exception is org.springframework.beans.factory.
NoSuchBeanDefinitionException: No qualifying bean found for dependency
[org.springframework.batch.item.ItemProcessor<com.abc.proj.model.FileHeader,
com.abc.proj.model.FileHeader>]: expected at least 1 bean which qualifies as
autowire candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true),
#org.springframework.beans.factory.annotation.Qualifier(value=headerProcessor)}
#Component
public class DelegateProcessor implements ItemProcessor<Object, Object>, InitializingBean {
#Autowired
#Qualifier("headerProcessor")
private ItemProcessor<FileHeader, FileHeader> headerProcessor;
#Autowired
#Qualifier("detailProcessor")
private ItemProcessor<FileDetail, FileDetail> detailProcessor;
#Autowired
#Qualifier("trailerProcessor")
private ItemProcessor<FileTrailer, FileTrailer> trailerProcessor;
#Component
public class HeaderProcessor implements ItemProcessor<Object, Object>{
#Autowired
private HeaderValidatorDao headerValidatorDao ;**
With a configuration class you could initialize your beans manually, specially if they need custom names.
#Configuration
public class MyCustomConfiguration {
#Bean(name ="headerProcessor")
public ItemProcessor<FileHeader, FileHeader> headerProcessorBean() {
ItemProcessor<FileHeader, FileHeader> myBean = new HeaderProcessor<>();
//Do whaterever you need to initilize your bean
return myBean;
}
#Bean(name ="detailProcessor")
public ItemProcessor<FileDetail, FileDetail> detailProcessorBean() {
ItemProcessor<FileDetail, FileDetail> myBean = new ItemProcessor<>();
//Do whaterever you need to initilize your bean
return myBean;
}
}
In this way these beans will be available for autowiring.

Spring Data JDBC UnsatisfiedDependencyException

I wanted to move from JdbcTemplate to Spring Data JDBC. However I seem to have some misconfiguration but I cannot figure out where. The errors are "expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}" and "Parameter 0 of constructor ... required a bean ... that could not be found."
I put #Repository on the public repository interfaces extending PagingAndSortingRepository (as I did with the DAO classes extending from JdbcDaoSupport) without success. Then I added #EnableJdbcRepositories with and without package name to the database config class, also no success. I also tried the database config to inherit from AbstractJdbcConfiguration, still the same errors ...
Unfortunately I couldn't find a working example and I now gave up after some trial and error. I still would love to get this working, the version I used is spring-boot-starter-data-jdbc:2.4.0
Code fragments:
DatabaseConfiguration.java
#Configuration
#EnableJdbcRepositories("<basepackage>.repository.jdbc")
#EnableJdbcAuditing(auditorAwareRef = "springSecurityAuditorAware")
#EnableJpaRepositories("<basepackage>.repository")
#EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
#EnableTransactionManagement
#EnableElasticsearchRepositories("<basepackage>.repository.search")
public class DatabaseConfiguration extends AbstractJdbcConfiguration {
}
UserRepository.java
#Repository
public interface UserRepository extends PagingAndSortingRepository<User, String> {
}
QualityResource.java (REST Controller)
public QualityResource(UserRepository userRepository) {
this.userRepository = userRepository;
}
Error messages:
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'qualityResource' defined in file [.../backend/build/classes/java/main/.../web/rest/QualityResource.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '....repository.jdbc.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Application failed to start: Description: Parameter 0 of constructor in <basepackage>.web.rest.QualityResource required a bean of type '<basepackage>.repository.jdbc.UserRepository' that could not be found.

No qualifying bean of type 'ThreadPoolTaskExecutor' available

I'm using Spring Boot 2.2.4 and I'm trying to a custom Executor
Below are the relevant classes
#Configuration
#ManagedResource
public class ExecutorConfig {
#Bean(name = "detailsScraperExecutor")
public Executor getDetailsAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setQueueCapacity(1000000);
executor.setThreadNamePrefix("detailsScraperExecutor-");
executor.initialize();
return executor;
}
}
and the following class which tries to use it.
#Component
#Profile("!test")
public class DetailsScraper {
private static final Logger logger = LoggerFactory.getLogger(DetailsScraper.class);
#Autowired
#Qualifier("detailsScraperExecutor")
private ThreadPoolTaskExecutor detailsScraperExecutor;
}
When I run the application I get the following error
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'detailsScraper': Unsatisfied dependency
expressed through field 'detailsScraperExecutor'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true),
#org.springframework.beans.factory.annotation.Qualifier(value="detailsScraperExecutor")}
my application.properties
spring.jmx.enabled=false
spring.datasource.url=jdbc:postgresql://example.com:5432/example
spring.datasource.username=example
spring.datasource.password=password
spring.jpa.open-in-view=false
logging.level.com.gargoylesoftware.htmlunit=ERROR
spring.datasource.hikari.maximumPoolSize = 30
app.properties.parseaddress.endpoint=http://example.com
Even though I have named it detailsScraperExecutor Spring can't find it? Why is that?
You need to inject the same type of class as declared in configuration but not a higher-level one. But you can use the lower-level one.
#Autowired
private Executor detailsScraperExecutor;

struts2 + spring4 + mybatis3 if use #Transactional will be a mistake (Autowired(required=true))

I am using spring #Transactional to manage MySQL transactional.
But the way I add #Transactional is wrong.
#Service
//#Transactional(readOnly = true)
public class UserInfoService extends BaseService
#Autowired
private UserInfoAccessor userInfoAccessor;
//#Transactional
public void insert()
Map<String, String> map = new HashMap<>();
map.put("userName", "test");
userInfoAccessor.insert(map);
The error message I receive is:
Unable to instantiate Action, com.luotuo.xiaobao.action.IndexAction, defined for 'index' in namespace '/'Error creating bean with name 'com.luotuo.xiaobao.action.IndexAction': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.luotuo.xiaobao.service.UserInfoService com.luotuo.xiaobao.action.IndexAction.userInfoService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.luotuo.xiaobao.service.UserInfoService] 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)
You can download my project source here.
What is the correct way to set this up?

#Autowired not working for interface

I am trying all the solutions from Google from last 4 days. but not working.
I am trying to autowire below Interface -
#Qualifier("roleAccessRepository")
#Repository
public interface RoleAccessRepository extends BaseJPACrudRepository<RoleAccess, Long> {
in PermissionEvaluator in following way.But its not working.
#Scope(proxyMode = ScopedProxyMode.INTERFACES, value = "prototype")
public class PermissionEvaluator implements org.springframework.security.access.PermissionEvaluator
{
#Autowired
RoleAccessRepository roleAccessRepository;
..........
Giving me error -
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: net.pa
ger.lrs.sql.db.RoleAccessRepository net.pager.lrs.security.PermissionEvaluator.roleAccessRepository;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying
bean of type [net.pager.lrs.sql.db.RoleAccessRepository] found for dependency: expected at least 1 b
ean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springf
But Repository defined in the same package and autowired in service class are working good.
#Service
#Transactional
public class AccountService extends BaseCrudService<Account> {
/** The account db. */
#Autowired
private AccountRepository accountDB;
}
My security.xml is as follows - which has base package net.pager.lrs which is parent directory.
<bean id="permissionEvaluator" class="net.pager.lrs.security.PermissionEvaluator">
<constructor-arg index="0">
Please help me.
Ok,
From the discussions above, I still think that the problem is with not having the concrete implementation of the Autowired interfaces. Just for the sake of common sense, if you do not provide an implementation, what will you execute using the reference of the Autowired interface.
There is a way where you do not define the implementation, spring can generate proxy beans and autowire, but that is of no use.
You might end up providing an anonymous implementation of the interface as well.

Resources