使用注解创建时,默认情况下如何命名Bean? [英] How are beans named by default when created with annotation?

查看:104
本文介绍了使用注解创建时,默认情况下如何命名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.

推荐答案

是注释的默认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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆