You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Spring Boot中context.getBean按名称获取抛出NoSuchBeanDefinitionException问题

如何通过名称获取Spring Boot中@Controller注解的Bean?

我有一个Spring Boot应用,调用context.getBean(MyController.class)时可以正常获取Bean,但调用context.getBean("MyController")context.getBean("com.MyController")时会抛出NoSuchBeanDefinitionException。请问如何通过名称获取该Bean?

我的代码示例

Application类

package com; 
import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 
import org.springframework.context.ConfigurableApplicationContext; 

@SpringBootApplication 
public class Application { 
    public static void main(String[] args) throws Exception { 
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args); 
        // MyController myController = (MyController) context.getBean("com.MyController"); // 抛出NoSuchBeanDefinitionException
        // MyController myController= (MyController) context.getBean("MyController"); // 抛出NoSuchBeanDefinitionException
        MyController myController = (MyController) context.getBean(MyController.class); // 正常工作
        System.out.println(myController); 
    } 
} 

MyController类

package com; 
import org.springframework.stereotype.Controller; 

@Controller 
public class MyController { } 

问题原因 & 解决方案

问题出在Spring对@Controller注解Bean的默认命名规则上,下面是几种可行的解决方式:

1. 使用Spring默认生成的Bean名称

Spring默认会把类名的首字母小写作为Bean的名称,所以你的MyController对应的Bean名称是myController(注意首字母小写)。直接用这个名称就能获取:

MyController myController = (MyController) context.getBean("myController");

2. 自定义Bean名称

如果你想使用自己指定的名称(比如MyController),可以在@Controller注解里显式指定Bean名称:

@Controller("MyController") // 自定义Bean名称
public class MyController { }

之后就可以用context.getBean("MyController")正常获取了。

3. 使用全类名作为Bean名称

如果想把全类名com.MyController作为Bean名称,可以通过配置Spring的Bean命名策略实现:
application.properties中添加配置:

spring.main.bean-naming-strategy=org.springframework.context.annotation.FullyQualifiedAnnotationBeanNameGenerator

或者在application.yml中:

spring:
  main:
    bean-naming-strategy: org.springframework.context.annotation.FullyQualifiedAnnotationBeanNameGenerator

配置完成后,就能用context.getBean("com.MyController")获取到对应的Bean了。

内容的提问来源于stack exchange,提问作者xingbin

火山引擎 最新活动