I have came across a weird behavior in my java class and wanted to understand what is the cause of such behavior, since investigating online didn't result with anything similar to my situation, I had to ask.
My java program using Spring Framework has a class named Validator
, it's definition is as follows:
@Component
public class Validator {
...
}
Now, in many other places in my code I use this class with @Autowired
annotation, like:
@Autowired
Validator validator;
When I try to fire up my service my .war
fails with error:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.common.validators.Validator]
But if I add name to the @Component
annotation like this:
@Component("Validator")
public class Validator {
...
}
it works perfectly fine.
Why do I have to state the name of the validator class in the @Component
annotation, when it is the same name? I have noticed that if I change my class name to anything else, for example: GeneralValidator
it works fine without stating the name in the @Component
.
This is because of a conflict with org.springframework.validation.Validator (documented here), please note the documentation of the optional argument for the @Component (here)
The value may indicate a suggestion for a logical component name, to be turned into a Spring bean in case of an autodetected component.