【发布时间】:2018-10-02 01:17:48
【问题描述】:
我正在SpringBoot中构建一个“hello world”的基本程序
代码
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
错误
线程“main”中的异常 org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 名为“myController”的 bean 可在 org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:686) 在 org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1210) 在 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291) 在 org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) 在 org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089) 在 di.prac.DemoApplication.main(DemoApplication.java:16)
请找出项目中的错误并解释
【问题讨论】:
-
您的控制器与您的演示应用程序类位于不同的包中。
-
将
MyController放入di.prac。这将允许 spring boot 执行自动组件扫描
标签: java spring spring-boot