我有一个春季启动应用程序。当我拨打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);
}
}
控制器:
package com;
import org.springframework.stereotype.Controller;
@Controller
public class MyController {
}
答案 0 :(得分:2)
您还可以在MyController类中定义控制器的名称,如下所示,
@Controller(value="MyController")
public class MyController {
}