Home > Enterprise >  is @ComponentScan really optional?
is @ComponentScan really optional?

Time:04-18

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:

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)

CodePudding user response:

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.

  • Related