user496949
user496949

Reputation: 86075

Is spring getbean case sentitive or not?

when I use getBean("test")

I have a class like

@Component
public class TEST {
}

can this bean be loaded?

Upvotes: 23

Views: 11871

Answers (2)

vertti
vertti

Reputation: 7879

@Component annotation uses AnnotationBeanNameGenerator by default which, if not explicitly given a name, will use Introspector.decapitalize() method on the bean ClassName to get a name for the bean. Normally a class with name like "Test" will give it bean name "test". But decapitalize has a curiosity:

This normally means converting the first character from upper case to lower case, but in the (unusual) special case when there is more than one character and both the first and second characters are upper case, we leave it alone.

So your class TEST will get bean name TEST.

Upvotes: 13

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340723

getBean() is case sensitive, however Spring uses custom bean naming strategy for @Component and @Bean classes. See 4.10.5 Naming autodetected components:

When a component is autodetected as part of the scanning process, its bean name is generated by the BeanNameGenerator strategy [...]. By default, any Spring stereotype annotation (@Component, @Repository, @Service, and @Controller) that contains a name value will thereby provide that name to the corresponding bean definition.

If such an annotation contains no name value or for any other detected component (such as those discovered by custom filters), the default bean name generator returns the uncapitalized non-qualified class name.

And for @Configuration/@Bean see 4.12.4.5 Customizing bean naming:

By default, configuration classes use a @Bean method's name as the name of the resulting bean. This functionality can be overridden, however, with the name attribute.

Back to your question. Because your class is not following Java naming conventions (camel-case names) Spring uses unusual name for the bean, this will work:

getBean("TEST")

However if you use expected naming (@Component class Test { }), you must use lower-case identifiers:

getBean("test")

Moreover if your name is more complex, uncapitalized camel-case syntax applies (continuing to quote the Spring documentation):

[...] For example, if the following two components were detected, the names would be myMovieLister and movieFinderImpl:

@Service("myMovieLister")
public class SimpleMovieLister {
  // ...
}

@Repository
public class MovieFinderImpl implements MovieFinder {
  // ...
}

Upvotes: 27

Related Questions