问题
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