SpringBoot error : No bean named 'myController' available
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.
For your controller to be available in the context of Spring, you need to define that it is managed by the Spring container. Only the @Controller annotation is not enough, it indicates only the stereotype of your bean, as well as the annotations @Repository and @Service.
In cases where the beans have these annotations and are managed by Spring, it is because their packages that the spring is scanning to search for them has been specified programmatically or per xml. In your case, you should annotate your DemoApplication class with 2 other annotations:
- @Configuration - Allows access to spring context
@ComponentScan - Packages to be scanned by Spring
@Configuration @ComponentScan (basePackages = {"controllers"}) 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())); } }