gpt4 book ai didi

java - spring getbean 是否区分大小写?

转载 作者:IT老高 更新时间:2023-10-28 13:53:43 24 4
gpt4 key购买 nike

当我使用 getBean("test")

我有一门课

@Component
public class TEST {
}

这个 bean 可以加载吗?

最佳答案

getBean() 区分大小写的,但是 Spring 对 @Component@Bean 使用自定义 bean 命名策略> 类(class)。见 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.

@Configuration/@Bean4.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.

回到你的问题。因为您的类不遵循 Java 命名约定(驼峰命名),所以 Spring 为 bean 使用了不寻常的名称,这将起作用:

getBean("TEST")

但是,如果您使用预期命名(@Component class Test { }),则必须使用小写标识符:

getBean("test")

此外,如果您的名字更复杂,则适用未大写的驼峰式语法(继续引用 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 {
// ...
}

关于java - spring getbean 是否区分大小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10967279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com