views:

363

answers:

7

Hi all,

I understand the IOC concept, which we can mix-and-match different classes using wiring. Every class can get away from hard code it's dependancy by delegating the wiring / relationship handling to base xml (context xml).

Here is my question, why do we use xml? we can simply wire all the components by using java class. Instead of

<bean id="helloWorld" class="com.vaannila.HelloWorld">
 <property name="message" value="HelloWorld"></property>
</bean>

public static void main(String[] args)
{
    // TODO Auto-generated method stub
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
    helloWorld.display();
}

We can rewrite them using

HelloWorld helloWorld = new HelloWorld();
helloWorld.setMessage("HelloWorld");
helloWorld.display();
+5  A: 

Check out Spring JavaConfig.

Nate
+8  A: 

That's basically the approach that Guice takes, yes.

There are advantages to using XML (or some other similar text-based approach though). In particular, you can change your application's wiring without rebuilding anything. If you don't want that, you can certainly do it all by hand or use something like Guice.

Additionally, Spring uses the fact that it's all configured declaratively to enable things like AOP. You can do all of that by hand, but it's a bit more long-winded.

Jon Skeet
As soneone else noted, Spring can also utilize configuration in Java via JavaConfig, so Guice is not a requirement to implement programatic configuration.
Rich Kroll
True - certainly not a requirement. Just an approach which takes programmatic configuration as the starting point.
Jon Skeet
A: 

It gives you some freedom in the field to be able to modify the construction or configuration of the application.

e.g. at a client site, without access to a compiler (or perhaps on a production machine), I can change components around, modify database configurations, change logging levels etc. Alternatively, I can give the configs to someone who doesn't/can't write code, and they can make (albeit simple) changes to the application (you have to be careful with this, of course).

It's the same argument for all configurations. You can do it all in code. But when is it appropriate ?

Brian Agnew
The "it's not code and therefore people who are too stupid to understand code can change it" argument is IMO total rubbish. Code, in any other guise (including XML), is still instructions to the computer that can be wrong, need to be tested, etc. And in most cases, an appropriate subset of a real programming language would in fact be EASIER to understand and change than some half-assed home-cooked config file format.
Michael Borgwardt
I think you're putting words in my mouth. I didn't make any such assertion about the intelligence or abilities of my clients (beyond the fact that they may not be Java programmers). If you feel you have a valid point, I'd try to make it using less contentious and inflammatory language.
Brian Agnew
+5  A: 

Some people have the strange idea that XML is not code, and so is magically different from code. Sometimes you have to tolerate people with that idea.

soru
A: 

Wiring up your beans like this

HelloWorld helloWorld = new HelloWorld();
helloWorld.setMessage("HelloWorld");
helloWorld.display();

Might make sense when you have a small number of beans in your environment.

But what if you have a more complicated environment in which you have dozens or hundreds of beans in Spring? My current application has around 205 beans mapped in about four different XML files. Wiring these up in code would be a nightmare.

matt b
No. Why would it be any more difficult than an XML file?? In fact, I bet it would be easier. Debugging, IDE refactoring support, etc.
Michael Borgwardt
Actually, the Spring IDE plugin for Eclipse takes care of refactoring support. I'd think it'd be harder because the wiring up would take around 1000 lines or more...
matt b
+2  A: 

I would say that the reason Spring favors XML over Java is that the two languages are for two different tasks. Java is a programming language. Its purpose is to describe algorithms, programs, control flow, etc. If deducing the structure of your program requires complex control flow, Java would be a good choice.

XML is fundamentally different. It is not a programming language. It is a way to describe ordered data, like a cookbook or a vector graphic. If the organization and interdependencies of your program's system are static values, then XML might be an appropriate place to put them.

I would argue that your configuration stuff should generally not be in Java for the same reason that a cookbook should not be in Java. In fact, I could make the same conversion:

<book>
  <chapter>It was the best of times, it was the worst of times</chapter>
</book>

public static void main(String[] args)
{
    String chapter1 = BookXMLParser.loadChapter(1);
    System.out.println(chapter1);
}

could obviously also be done entirely in Java:

public static void main(String[] args)
{
    String chapter1 = "It was the best of times, it was the worst of times");
    System.out.println(chapter1);
}

Now, obviously, this is a ridiculous example. Books are hundreds of pages long. It would be silly to keep them in Java code. However, I would make the same argument for Spring configuration. One of my largest programs has spring XML that totals to many thousand lines.

Of course, there's definitely something to be said in favor defining this stuff in Java. Most especially, IDEs would be able to provide additional help more easily about which classes are using what, and other static analysis tools would be a little better at analyzing your code for problems as well.

Then again, there are also some downsides. Allowing you to do this configuration in Java allows the programmer to do all sorts of nasty things that are significantly harder to achieve in XML, like this:

bean1.setName("fred");
if( System.currentTimeMillis() > 1234567890l ) {
   //Automatically use new feature after next Thursday
   bean1.setNewFeature(1);
} else if( x > 17 ) {
  switch(y) {
   case POTATO:
     bean1.setNewFeature(0);
     break;
   case POTAHTO:
     bean1.setNewFeature(1);
   case WHO_COULD_ASK_FOR_ANYTHING_MORE_FALLTHROUGH:
     bean1.setFoo(bar);
     break;
   default:
     baz? bean1.setBar(baz) : if(17 > t) 
         { bean1.setNewFeature(q) } else {
          throw new RuntimeException("That's odd...");
         }
  }
}

Well, you get the point. Your code obviously won't start out that bad, but you'll be tempted to use an if statement somewhere, and then you'll use another, and then another....

CaptainAwesomePants
What in the world gave you the idea that a cookbook is a good example for something that isn't a programming language? Case in point: http://www.dangermouse.net/esoteric/chef.html
Michael Borgwardt
I was discussing a recipe book as the sort of thing that was generally structured data. But your point that a recipe is basically an algorithm is fascinating. I imagine that there are some fairly elegant algorithms for creating Sierpinski Cakes, but I'd hate to get caught in an infinite loop.
CaptainAwesomePants
A: 

"I understand the IOC concept, which we can mix-and-match different classes using wiring."

How can it be that you claim on one hand to understand the IoC concept and in the next breath offer a "hello world" example that doesn't use any of it? I don't get it.

XML isn't 100% necessary. Even Spring gives the option of using mostly annotations now. Do they change your view?

All the things that Spring can do for you with dynamic proxies as a result of IoC would be hard to reproduce for yourself with hand-written code.

UPDATE: You'd have to go back and ask Rod Johnson why he chose XML, but it's easy to defend. When he was developing the idea for his consulting gigs back around 2000-2002 XML was commonly used.

Spring happens to use XML to externalize configuration, but you're free to use annotations if you've got Spring 2.5 or higher.

Your question confuses me because the example you gave that uses Java code isn't IoC at all. You're not wiring anything when you call new that way. I'd recommend going back and reading Martin Fowler's IoC article again: http://www.martinfowler.com/articles/injection.html

duffymo
I am sorry if I didn't make myself clear. I didn't question if Spring a good framework or not. I was asking why Spring uses XML, instead of Java code to wire up the component :)
janetsmith