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

前端之家收集整理的这篇文章主要介绍了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

猜你在找的Springboot相关文章