Reputation: 28269
I have a spring boot application. When I call context.getBean(MyController.class)
, it works fine. When I call context.getBean("MyController")
or context.getBean("com.MyController")
, NoSuchBeanDefinitionException
is thrown. How to get the bean with its name?
Application
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
// MyController myController = (MyController) context.getBean("com.MyController"); NoSuchBeanDefinitionException
// MyController myController= (MyController) context.getBean("MyController"); NoSuchBeanDefinitionException
MyController myController = (MyController) context.getBean(MyController.class); // works fine
System.out.println(myService);
}
}
Controller:
package com;
import org.springframework.stereotype.Controller;
@Controller
public class MyController {
}
Upvotes: 0
Views: 607
Reputation: 6808
You can also define name of controller in your MyController class as below,
@Controller(value="MyController")
public class MyController {
}
Upvotes: 2