V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
persona5
V2EX  ›  程序员

Spring 中通过 ApplicationContext 获取 service bean 时发现 beanName 突然变成类全限定名?

  •  
  •   persona5 · 2022-11-16 09:23:05 +08:00 · 1044 次点击
    这是一个创建于 526 天前的主题,其中的信息可能已经有所发展或是发生改变。

    环境是 springboot 2.3.3 ,JDK 11 。

    @Slf4j
    @Service
    public class TestServiceImpl extends ... implements ... {
    	...
    }
    

    通过 ApplicationContext (或者 hutool 的 SpringUtil 之类的工具类)获取 bean

    @Autowired
    private ApplicationContext ctx;
    
    
    Object bean = ctx.getBean("testServiceImpl");
    

    出现异常

    org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'testServiceImpl' available
    

    按照我的理解,@Service 中我没有指定 beanName ,默认的就应该是 testServiceImpl 吧?并且以前就是这么使用的,没有遇到过问题。

    然后尝试通过 Class 获取

    // [com.xxx.xxx.service.impl.TestServiceImpl]
    String[] arr = ctx.getBeanNamesForType(TestServiceImpl.class);
    
    // {com.xxx.xxx.service.impl.TestServiceImpl = com.xxx.xxx.service.impl.TestServiceImpl@5a48da4f}
    Map<String, TestServiceImpl> beansOfType = ctx.getBeansOfType(TestServiceImpl.class);
    

    从日志输出结果来看,beanName 是类的全限定名,随后尝试用 getBean(类的全限定名) 可以获取到 service 。

    就算我在 @Service 注解中指定 beanName ,@Service("testServiceImpl"),上面两个的输出也还是类的全限定名。

    请问这是什么问题?我的目标是希望能够用 getBean("testServiceImpl") 来获取,testServiceImpl 实际上是一个传进方法的变量。

    3 条回复    2022-11-17 09:39:14 +08:00
    kissice
        1
    kissice  
       2022-11-16 09:30:04 +08:00   ❤️ 1
    看下程序入口处是不是加了下面这个注解,如果是去掉就行了,一般来说程序里有同名不同包的类才会考虑用这个注解
    @ComponentScan(nameGenerator = FullyQualifiedAnnotationBeanNameGenerator.class)
    persona5
        2
    persona5  
    OP
       2022-11-16 09:37:24 +08:00
    @kissice 感谢提醒,是这个类似的原因。

    没注意什么时候 Application 上面的 @ComponentScan 有人指定了一个自定义的 nameGenerator ,然后在里面把 generateBeanName 重写成 definition.getBeanClassName() 了...
    duanguyuan
        3
    duanguyuan  
       2022-11-17 09:39:14 +08:00 via Android
    1 楼经验好丰富,膜拜大佬
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4643 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 05:35 · PVG 13:35 · LAX 22:35 · JFK 01:35
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.