How is Spring Container created?

2020-06-16 09:58发布

问题:

I am studying for the Spring Core certification and I have following doubt about this question:

What is meant by “container” and how do you create one?

I know that the Spring container is at the core of the Spring Framework. The container will create the objects, wire them together, configure them, and manage their complete lifecycle from creation till destruction. The Spring container uses dependency injection (DI) to manage the components that make up an application. These objects are called Spring Beans which we will discuss in next chapter.

And I know that there exist 2 containers:

  • Spring BeanFactory Container: This is the simplest container providing basic support for DI and defined by the org.springframework.beans.factory.BeanFactory interface. The BeanFactory and related interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean, are still present in Spring for the purposes of backward compatibility with the large number of third-party frameworks that integrate with Spring.

  • Spring ApplicationContext Container: This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners. This container is defined by the org.springframework.context.ApplicationContext interface.

Ok...this is pretty clear for me but what is the correct answer about How to create a container?

I think that it is automatically created by the Spring when it reads the configuration class or the XML configuration file.

Or not? What am I missing?

回答1:

In short, "The Container" is a Spring instance in charge of managing the lifecycle of your beans.

To create one, basically, you should do something like

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/application-context.xml");

Remember replacing /application-context.xml by the file where you define your own Spring beans.

Take a look at http://www.springbyexample.org/examples/intro-to-ioc-creating-a-spring-application.html

You could also substitute the xml by a configuration class. On that case you should have something like this:

@Configuration
public class Myconfig{

   @Bean 
   public MyBean myBean(){
      return new MyBean();
   }
}

For this, take a look at http://www.tutorialspoint.com/spring/spring_java_based_configuration.htm