Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does Spring use XML for component wiring?

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();   
like image 435
janetsmith Avatar asked Jul 14 '09 10:07

janetsmith


3 Answers

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.

like image 111
Jon Skeet Avatar answered Oct 15 '22 07:10

Jon Skeet


Check out Spring JavaConfig.

like image 29
Nate Avatar answered Oct 15 '22 09:10

Nate


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.

like image 38
soru Avatar answered Oct 15 '22 07:10

soru