Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpringBoot error : No bean named 'myController' available

I am building a basic program of "hello world" in SpringBoot

Code

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()));

    }
}

I am using eclipse and created this project from http://start.spring.io/ without any dependencies.

I learned that Spring create the bean of MyController class with name myController ,but Spring is not able to find myController bean

ERROR

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)

Please find and explain the error in the Project

like image 765
Ankit Halder Avatar asked Apr 21 '18 14:04

Ankit Halder


Video Answer


1 Answers

Place your controller under sub package of di.prac like di.prac.controllers or use @ComponentScan on your controller. By default, Spring scans the current and sub packages where your main application is present. If you want to scan other packages too, then you can specify the packages in @SpringBootApplication as an argument like.

@SpringBootApplication(scanBasePackages = {"com.xyz.controllers", "com.abc.models""})

We should avoid putting the @Configuration class in the default package (i.e. by not specifying the package at all). In this case, Spring scans all the classes in all jars in a classpath. That causes errors and the application probably doesn't start.

like image 118
Uzair Avatar answered Sep 24 '22 19:09

Uzair