java – SpringBoot错误:没有名为’myController’的bean可用

我正在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

错误

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)

请查找并解释项目中的错误

最佳答案
将控制器置于di.prac的子包下,如di.prac.controllers,或在控制器上使用@ComponentScan

转载注明原文:java – SpringBoot错误:没有名为’myController’的bean可用 - 代码日志