gpt4 book ai didi

java - context.getBean 抛出 NoSuchBeanDefinitionException

转载 作者:行者123 更新时间:2023-12-02 02:06:46 26 4
gpt4 key购买 nike

我有一个 Spring Boot 应用程序。当我调用 context.getBean(MyController.class) 时,它工作正常。当我调用 context.getBean("MyController")context.getBean("com.MyController") 时,会抛出 NoSuchBeanDefinitionException 。如何获取带有名称的 bean?

申请

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); // works fine
System.out.println(myService);
}

}

Controller :

package com;

import org.springframework.stereotype.Controller;

@Controller
public class MyController {
}

最佳答案

您还可以在 MyController 类中定义 Controller 名称,如下所示,

@Controller(value="MyController")
public class MyController {
}

关于java - context.getBean 抛出 NoSuchBeanDefinitionException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50647012/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com