我正在使用别人编写的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?
发布评论