Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

is @ComponentScan really optional?

I saw in a tutorial that says that using @ComponentScan in the java configuration file is optional but when I ran my code without @ComponentScan It gave me an error.

The code itself does not matter. I just added it for a better understanding

AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(SportConfig.class);

    Coach baseBallCoach= context.getBean("baseBallCoach", Coach.class);
    System.out.println(baseBallCoach.getDailyWorkout());
    System.out.println(baseBallCoach.getDailyFortune());
    context.close();

output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'baseBallCoach' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:863)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:309)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:213)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1160)
at org.isoft.Main.main(Main.java:14)

>Solution :

It is optional, but without it you will have by far more work with configuring all your beans. With @ComponentScan any class annotated with @Component @Service and few other annotations will be automatically discovered. If you don’t use @ComponentScan you have to define all your beans in @Configuration class with @Bean or in some other way. So, while @ComponentScan is optional you would want to use it in most cases.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading