0

I'm a noob when using Spring and I have a doubt.

When and where must I initialize the spring context?

Right now I am initializing the context when I'm going to use something like a properties file:

 ClassPathXmlApplicationContext cxt = new ClassPathXmlApplicationContext("myContext.xml");

But I have read that the Spring context must be initialized in the entry point of my program (Main.java) and pass it as argument in the necessary methods.

Is this true?

Bogdan
  • 23,890
  • 3
  • 69
  • 61
Juan Reina Pascual
  • 3,988
  • 7
  • 21
  • 34

2 Answers2

0

If you are talking about a web application, you should do it web.xml Loading context in Spring using web.xml

If it's a test, things are different: spring junit load application context for tests

In both cases, you don't need an explicit main.java

Community
  • 1
  • 1
Luís Soares
  • 5,726
  • 4
  • 39
  • 66
0

As @MarounMaroun said, it really depends on what are you trying to do.

When people use Spring they usually build the entire application to take advantage of what Spring has to offer. That is to say, they put everything in the Spring context, configure it, and let it wire all the things together when starting. So in order to be useful, the application needs to load the Spring context before doing anything else.

For a standalone application you do the initialization in the main method. When main is called, you first initialize the Spring context, and once the context is fully loaded you retain a reference to it and make it available where needed.

If it makes sense to initialize the Spring context at a later time or in another class you can do that too, but as I said, most applications need the context initialized to be able to function so that's why they initialize it as early as possible, in the main method, and that's probably the recommendation you have read.

Bogdan
  • 23,890
  • 3
  • 69
  • 61