0

I am learning Spring Framework. I have started with the core. I learn't the way to create Beans by specifying values in the XML file and then using Context (XML or Application) to initialize the bean. I am confused with this approach of creating objects via XML file (specifying value of constructors and setters method).
I feel my area of thinking is small. How Spring is helpful if I am creating a bean based on the values provided by user (through some fields)? I think in such scenarios, first I have to save those values in XML file and then initialize the bean via java code to get the object (If I am using spring framework).

My question is what is the benefit of having constructors initialized via XML file? In a basic java web application, I will create a bean based on the values provided by user (form fields) directly. I will never create an XML file (Spring Configuration), saving user input in that file then further initializing bean through Spring Context.

I hope I am able to explain my problem.

I can understand the benefit of DI and IOC but If anyone can explain me with a simple java example of a small program, where you are taking user input and saving it in DB (no need to write in detail code). How you will use the Constructor Injection or Setter Injection. The values provided by user are run time values.

Ravi.Kumar
  • 761
  • 2
  • 12
  • 34
  • possible duplicate of [What exactly is Spring for?](http://stackoverflow.com/questions/1061717/what-exactly-is-spring-for) – Joe Apr 07 '15 at 12:57

2 Answers2

2

Using constructor arguments helps to ensure your beans are not initialized without the necessary fields being set.

The use case of a web application is different: You really shouldn't have DTOs configured anyway (it's going to require a bunch of legwork on your part, as you're discovering). The main benefit Spring in a webapp would be to host service objects, DAOs and factories. For user-editable DTOs however, I see little benefit in configuring them in a file

TL;DR: Don't put your DTOs nakedly in the config file, rather, create a Factory for them to be managed by Spring

kolossus
  • 20,559
  • 3
  • 52
  • 104
  • I agree, if you are using DTOs, there is absolutely no need for any sort of configuration in the XML. – holtc Apr 07 '15 at 13:02
0

Specifying the beans in XML takes care to 3 main things that I can think of right now

  1. You don't have to create beans manually and just need to get it from application context.
  2. Thread management in this case is done by Spring OOTB, you don't have to worry about it
  3. It is easy, as once you define a bean you can reuse it again and again.
Rupesh
  • 2,627
  • 1
  • 28
  • 42