使用注解创建时,默认情况下如何命名Bean?

编程入门 行业动态 更新时间:2024-10-27 02:23:02
本文介绍了使用注解创建时,默认情况下如何命名Bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用别人编写的Spring Java代码.我想引用通过注释(字段classABC)创建的bean:

I am working with Spring java code written by someone else. I want to reference a bean that's created by annotation (of field classABC):

@Component public class ClassService { @Autowired ClassABC classABC; public interface ClassABC @Repository public class ClassABCImpl extends BaseABC implements ClassABC

以下代码尝试按名称获取对ClassABC bean的引用,但不起作用:

The following code tries to get a reference to the ClassABC bean by name, but does not work:

ClassABC classABC = ApplicationContext.getBean("classABC");

但是,以下按类型引用此bean的代码确实起作用:

However, the following code that references this bean by type does work:

ClassABC classABC = ApplicationContext.getBean(ClassABC.class);

因为第一个引用不起作用,所以我猜该bean没有命名为"classABC".这个豆叫什么名字?

Because the first reference does not work, I am guessing that the bean is not named "classABC". What is the name of this bean?

注意:没有配置XML引用此bean,因此我认为bean名称不在xml中定义.

Note: there is no configuration xml that references this bean, so I don't think the bean name is defined in xml.

推荐答案

docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/AnnotationBeanNameGenerator.html

是注释的默认bean名称生成器,对于@Bean

Is the default bean name generator for annotations, there's a DefaultBeanNameGenerator for beans defined by @Bean

在这种情况下,我相信Bean的名称将是classABCImpl,因为它是由类的短名称构建的.

In this case I believe the name of the bean would be classABCImpl, as its built of the short name of the class.

从具体的服务实现示例中, com.xyz.FooServiceImpl -> fooServiceImpl

From the example of a concrete service implementation, com.xyz.FooServiceImpl -> fooServiceImpl

如果您想通过名称来引用该bean,我个人不喜欢使用默认命名.在这种情况下,最好将其明确.

Personally I'm not a fan of using the default naming if you are ever going to want to refer to that bean via the name. Better to be explicit in these cases.

更多推荐

使用注解创建时,默认情况下如何命名Bean?

本文发布于:2023-11-05 19:25:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561647.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:注解   情况下   Bean

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!