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.