Is spring getbean case sentitive or not?

后端 未结 2 1377
小蘑菇
小蘑菇 2021-02-05 09:43

when I use getBean(\"test\")

I have a class like

@Component
public class TEST {
}

can this bean be loaded?

2条回答
  •  鱼传尺愫
    2021-02-05 09:58

    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 {
      // ...
    }
    

提交回复
热议问题