Search code examples
javaspringspring-ioc

About AnnotationConfigApplicationContext in Spring framework


I have written the following simple stand-alone spring app:

package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;

@Configuration
@ComponentScan(basePackages = { "com.example" })
@PropertySource(ignoreResourceNotFound = true, value = "classpath:/application.props")
public class MainDriver {

@Autowired
private Environment env;
@Autowired
private ApplicationContext ctx;
@Autowired
private ConfigurableEnvironment cenv;

public static void main(String[] args) {

    ApplicationContext ctx = new AnnotationConfigApplicationContext(MainDriver.class);
    MainDriver l = ctx.getBean(MainDriver.class);
    System.out.println("In main() the ctx is " + ctx);
    l.test();

}

public void test() {
    System.out.println("hello");
    System.out.println("env is " + env);
    System.out.println("cenv is " + cenv);
    System.out.println("ctx is" + ctx);
}
}

I understood that within main() we are Creating a new Application context and then creating Bean and eventually calling test() method.

What I am not able to understand how come Environment , ApplicationContext and ConfigurableEnvironment get Autowired (and to which bean?)

I observed that the autowired ctx gets the context which is initialise in main().

Basically not able to understand how these gets autowired by itself (and what they are set to?)

Any help in understanding this would be of great help.


Solution

  • Any class that is annotated with @Configuration is also a Spring bean. That means the MainDriver is also a Spring Bean that will be created during the creation of AnnotationConfigApplicationContext.

    And after the MainDriver bean is created, Spring will then inject other beans into its field if that field is annotated with @Autowired. So in this case , Environment , ApplicationContext, and ConfigurableEnvironment are all injected this MainDriver bean.

    P.S. You can think that Environment, ApplicationContext, and ConfigurableEnvironment are kind of Spring infrastructure beans that must be created even though you do not define them using @Configuration, @Service, @Bean and etc.