0
votes

Is ApplicationContext automatically instantiated in Spring?

If I have my bean defined like this

@Component
public class Car{
   ...
}

and then I have my config class which tells Spring container where to look for beans through the annotation @ComponentScan

@Configuration
@ComponentScan
public class AppConfig {
   ...
}

Is Spring automatically creating a context loading all my beans? Or do I have to create it programmatically? If so how do I do it, with something like this?

@Configuration
@ComponentScan
public class AppConfig {
   ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
   context.getBean(Car.class);
   ...
}

Even doing this, there may be a problem, because every time I need the context I have to call new AnnotationConfigApplicationContext... what is the recommended way to instantiate the context and making him available inside the whole project, maybe as a bean like inside Spring boot app where i can just autowire it.

How Spring Boot can initialize it, load all the beans and let the context available as a bean, ready to be autowired?

1

1 Answers

3
votes

No, Application Context isn't automatically instantiated, if you're having a simple and basic Spring Core application. Moreover, your @Configuration class won't scan anything and won't create any beans, if you don't create your Spring Container/Context explicitly with that @Configuration class.

There are several ways of creating Application Context, but the most popular and traditional ones are:

  • ApplicationContext context = new ClassPathXmlApplicationContext(applicationContext.xml) - implying, that you have your container configuration in the applicationContext.xml file;
  • ApplicationContext context = new AnnotationConfigApplicationContext(ConfigClass.class); - implying, that your ConfigClass is the @Configuration class.

However, if you have the Spring Boot application annotated with @SpringBootApplication, then the Application Context will be automatically instantiated for you, because:

@SpringBootApplication annotation consists of:

  • @EnableAutoConfiguration - which enables Spring Boot’s auto-configuration mechanism;
  • @ComponentScan - which enable @Component scan on the package where the application is located;
  • @Configuration - allows to register extra beans in the context or import additional configuration classes.

and this will spin up the context for you.

You can obtain the reference to the Spring Context created by Spring Boot, by the factory method you have in your main method: SpringApplication.run(MainClass.class, args);

This returns the reference to the Application Context and you can assign it to variable like this:

ApplicationContext context = SpringApplication.run(MainClass.class, args)