How are beans named by default when created with annotation?

不打扰是莪最后的温柔 提交于 2020-02-04 01:55:32

问题


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

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

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

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

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

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

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


回答1:


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

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

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

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

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.




回答2:


Adding to Darren Forsythe's answer above, the implementation of AnnotationBeanNameGenerator can result in two kinds of bean names.

If the short name derived from the class name starts with two uppercase characters, the short name will become the bean name. Otherwise if one of the first two characters of short name is lower case, the bean name would be the short name with the first character in lower case.

Example: com.xyz.FooServiceImpl class name leads to a short name of FooServiceImpl. Since, first two characters are not uppercase, the bean name would become -> fooServiceImpl.

However, if class name is com.xyz.FOoServiceImpl which leads to a short name of FOoServiceImpl, your bean name would remain FOoServiceImpl since the first two characters are uppercase.

Similarly, com.xyz.FOoServiceIMPL, will lead to bean name as FOoServiceIMPL.

Spring only looks at the short name and its first two characters while creating the bean name.



来源:https://stackoverflow.com/questions/48871789/how-are-beans-named-by-default-when-created-with-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!