码
MyController.java
package controllers; import org.springframework.stereotype.Controller; @Controller public class MyController { public String hello() { System.out.println("Hello World"); return "foo"; } }
DemoApplication.java
package di.prac; import java.util.Arrays; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import controllers.MyController; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { ApplicationContext ctx=SpringApplication.run(DemoApplication.class,args); MyController m = (MyController)ctx.getBean("myController"); m.hello(); System.out.println("*******"+Arrays.asList(ctx.getBeanDefinitionNames())); } }
我正在使用eclipse并从http://start.spring.io/创建了这个项目而没有任何依赖.
我了解到Spring使用名称myController创建了MyController类的bean,但Spring无法找到myController bean
Exception in thread “main”
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named ‘myController’ available at
org.springframework.beans.factory.support.DefaultListablebeanfactory.getBeanDefinition(DefaultListablebeanfactory.java:686)
at
org.springframework.beans.factory.support.Abstractbeanfactory.getMergedLocalBeanDefinition(Abstractbeanfactory.java:1210)
at
org.springframework.beans.factory.support.Abstractbeanfactory.doGetBean(Abstractbeanfactory.java:291)
at
org.springframework.beans.factory.support.Abstractbeanfactory.getBean(Abstractbeanfactory.java:199)
at
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089)
at di.prac.DemoApplication.main(DemoApplication.java:16)
请查找并解释项目中的错误