when I use getBean("test")
I have a class like
@Component
public class TEST {
}
can this bean be loaded?
getBean. Return an instance, which may be shared or independent, of the specified bean. This method allows a Spring BeanFactory to be used as a replacement for the Singleton or Prototype design pattern. Callers may retain references to returned objects in the case of Singleton beans.
getBean() method. Simply put, as the name of the method also suggests, this is responsible for retrieving a bean instance from the Spring container.
The default bean name will be method name. It means first bean name is getBeanA and second bean name is getBeanB . A bean can be accessed by bean class or bean name or can be injected in component using @Autowired annotation.
Bean life cycle is managed by the spring container. When we run the program then, first of all, the spring container gets started. After that, the container creates the instance of a bean as per the request, and then dependencies are injected. And finally, the bean is destroyed when the spring container is closed.
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 aname
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 thename
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
andmovieFinderImpl
:
@Service("myMovieLister")
public class SimpleMovieLister {
// ...
}
@Repository
public class MovieFinderImpl implements MovieFinder {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With