AndreaNobili
AndreaNobili

Reputation: 43017

How is Spring Container created?

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:

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?

Upvotes: 8

Views: 8416

Answers (1)

Andres
Andres

Reputation: 10725

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

Upvotes: 5

Related Questions