本文介绍了使用注解创建时,bean 是如何默认命名的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用其他人编写的 Spring Java 代码.我想引用一个由注释创建的 bean(字段 classABC):

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,所以我认为xml中没有定义bean名称.

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

推荐答案

https://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 是如何默认命名的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 07:09