Situation: I have I class with property annotated with #Autowired:
public class MyClass {
#Autowired
protected MyAutoWiredBean myAutowiredBean;
}
Is there any possibility to made wiring this bean optional, i.e. if such bean is defined in some configuration file - to wire it, but if such bean is not defined - just continue working without throwing:
org.springframework.beans.factory.BeanCreationException:
Could not autowire field: protected MyAutoWiredBean...;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No matching bean of type [com.mypackage.MyAutoWiredBean] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
Have you tried:
#Autowired(required=false)
Javadoc:
Declares whether the annotated dependency is required. Defaults to true
you can set required attribute like :
#Autowired(required=false)
http://static.springsource.org/spring/docs/2.5.5/api/org/springframework/beans/factory/annotation/Autowired.html
Related
**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.
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.
I am trying to create a bean that is valid only for a single request that contains a user's roles. I will populate the roles in an #Around method prior to calling any controller methods. I then need to access these roles later for other authorization checks.
#Component
#Aspect
public class SecurityAudit {
#Autowired
private CurrentRoles currentRoles;
#Around("#annotation(requestMapping) && execution( *
com.myapp.controller..*.*(..))")
public Object around(ProceedingJoinPoint pjp, RequestMapping requestMapping)
throws Throwable {
...
...
//I populate the roles with a db lookup. They will be referenced here, and later in controller methods as-needed.
}
}
package com.myapp.model;
...
...
#JsonInclude(JsonInclude.Include.NON_NULL)
#Generated("org.jsonschema2pojo")
#JsonPropertyOrder({
"sso",
"roles"
})
#Component
#Scope(value="request", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class CurrentRoles {
#JsonProperty("roles")
private Set<Role> roles;
...
...
}
I get the following:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityAudit': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.myapp.model.CurrentRoles com.myapp.currentRoles; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.myapp.model.CurrentRoles] 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)}
The Aspect is created at startup. I would have though the injected request-scoped bean would stay null until requests start coming in, then I could populate the currentRoles bean for that specific request.
Most probably you forgot #Service annotation in your Service class ;)
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?
I'm currently testing spring data rest, and I want to expose the primary keys (ids) of my entities through the REST interface.
I have found that the proper (?) way to do this is:
public class IdExporterConfiguration extends RepositoryRestMvcConfiguration {
#Override
protected void configureRepositoryRestConfiguration(
RepositoryRestConfiguration config) {
super.configureRepositoryRestConfiguration(config);
config.exposeIdsFor(User.class);
}
}
The problem is, that if I change my bean definition to this:
<bean class="test.project.util.IdExporterConfiguration"/>
From this:
<bean class="org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration"/>
my application fails to start...
The error is:
Could not autowire field: org.springframework.data.geo.GeoModule org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration.geoModule;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.data.geo.GeoModule] 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)}
Basically it says that it does not find a GeoModule bean, so it can't autowire it for the RepositoryRestMvcConfiguration base...
Now the fun part is, that is I define the bean:
<bean class="org.springframework.data.geo.GeoModule"/>
The error changes to:
Could not autowire field: org.springframework.data.geo.GeoModule org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration.geoModule;
nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.data.geo.GeoModule] is defined:
expected single matching bean but found 2: jacksonGeoModule,org.springframework.data.geo.GeoModule#0
So if I don't define a bean, there is 0, but if I define one, there is 2?
I still don't know why, but if I use the #Configuration annotation, then it works...
No GeoModule bean needed, but how can it be, that with the original config as XML bean definition it works, but with the subclass, it does not?