3

Ok, this question is gonna get a lot of downvotes...

I just saw this question where a guy is facing some issue with spring xml beanfactory thing.

I would like to understand why this:

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="namingStrategy">
        <ref bean="namingStrategy"/>
    </property>
    <property name="mappingResources">
        <list>
            <!--<value>genericdaotest/domain/Person.hbm.xml</value>-->
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
        </props>
    </property>
    <property name="dataSource">
        <ref bean="dataSource"/>
    </property>
</bean>

should be anyhow better than this:

public class BeanFactory {
    public LocalSessionFactoryBean getSessionFactory() {
        LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
        bean.setNamingStrategy(getNamingStrategy());
        bean.setMappingResources(Arrays.asList(getPerson());
        bean.setHibernateProperties(new Properties() {{ 
           setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
           setProperty("hibernate.show_sql", "true")
           setProperty("hibernate.hbm2ddl.auto", "create");
        }});
        bean.setDataSource(getDataSource());
        return bean;
    }
}

It's shorter, it's easier to understand, it doesn't have Spring quirks, it doesn't require an external library to run (that may clash with others), it's step-by-step debuggable, it' unit testable, it doesn't need reflection, it potentially benefits of OOP, it's easier to refactor from your IDE, it's type checked at compile time, it's Java -not xml- and doesn't require to be parsed at runtime, when it compiles you know already that it is formally correct (and not discovering exceptions at runtime), and if you need to externalize some configuration parameter you use a properties file (that will contain real configuration).

And more than everything: I don't need a huge singleton class called "BeanFactory" in my code who's responsibility is to instantiate every kind of objects (like a huge and ugly service locator that has nothing to do with IoC principles).

So, the question is:

why should I prefer creating a huge XML over creating my objects composing and aggregating them in Java?

5
  • 4
    I'm detecting some bias in this question. ;-)
    – Jonathan
    Jan 8, 2013 at 16:41
  • it's because I've been forced to use spring all the time :)
    – Luigi
    Jan 8, 2013 at 16:41
  • 4
    A huge mess of XML has never made sense to me. AFAIK The Spring guys often point out you can Spring without XML. Jan 8, 2013 at 16:41
  • Based on your comments, I'm having a hard time telling if you're legitimately looking for an answer or just looking for a place to complain about spring. Has your question been answered?
    – Jason
    Jan 9, 2013 at 1:02
  • Are my comments not pertinent to the answers?
    – Luigi
    Jan 9, 2013 at 1:26

6 Answers 6

6

Using a relatively modern version of Spring you are not forced to use xml at all. Simply annotate your class as follows...

@Configuration
public class BeanFactory {
     @Bean
     public LocalSessionFactoryBean sessionFactory() {
         LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
        bean.setNamingStrategy(getNamingStrategy());
        bean.setMappingResources(Arrays.asList(getPerson());
        bean.setHibernateProperties(new Properties() {{ 
           setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
           setProperty("hibernate.show_sql", "true")
           setProperty("hibernate.hbm2ddl.auto", "create");
        }});
        bean.setDataSource(dataSource());
        return bean;
    }

    @Bean
    public DataSource dataSource() { 
    ....
}

The real benefit of dependency injection is in the classes that use your beans. Your code isn't cluttered with plumbing code, it is focused on solving the business problem.

6
  • So basically I was using a more modern Spring, without using Spring :-). I know dependency injection, I just do it without Spring. Still how a BeanFactory concept fits with Dependency Injection remains a mystery to me.
    – Luigi
    Jan 8, 2013 at 17:24
  • The bean factory injects the beans you instantiate into collaborators. If you do this yourself, you would need to write your own framework or include a bunch of plumbing code in your beans either of which would be bad. I think you understand this but you just have a bias against spring. Your question was why you needed a mess of xml instead of using plain java. My answer shows that you can don't need any xml at all to use spring.
    – hyness
    Jan 8, 2013 at 18:35
  • 1
    We agree that Java for instantiating objects is better than XML (I'll probably accept your answer). I can't figure out how Spring (the xml thing) got a so wide adoption. I won't use a BeanFactory or any sort of central ServiceLocator unless my code asks for it; I usually pass dependencies on the constructors where I need to construct the objects, I never felt the need of a framework so far. My opinion is that spring beanfactory is a non-solution to a non-problem :)
    – Luigi
    Jan 8, 2013 at 18:40
  • "I usually pass dependencies on the constructors where I need to construct the objects" - this is fine when you're writing a simple application. I think you're failing to spot how badly this approach scales when you start writing a relatively complex application. Jan 8, 2013 at 18:48
  • But I've seen how bad it scales applicationContext.xml :)
    – Luigi
    Jan 8, 2013 at 19:02
1

A better question might be "What are the advantages of dependency injection?" After all, there are other dependency injection frameworks out there that use pure java instead of XML. (see Google Guice)

It all comes down to finding useful techniques to decouple your code and then 'wire' it together somewhere else.

2
  • I may like Guice, it's possible, Google stuff is always good quality. I'll give it a look (I confess my ignorance on it). BTW, you don't need necessarily a framework to do dependency injection, you just need an OOP language (and OOP languages are designed to scale).
    – Luigi
    Jan 8, 2013 at 22:35
  • I've had a quick look at Google Guice, and I am perplexed. It looks to me that what Guice does can be done better with plain java classes, without involving reflection. I'll study a bit more, and try to understand what I am missing, or maybe I'll come out with another question to show how I would have implemented the examples in Guice user guide, without Guice, and get some critics on the differences.
    – Luigi
    Jan 10, 2013 at 14:11
1

why should I prefer creating a huge XML over creating my objects composing and aggregating them in Java?

My understanding on the answers I received, is that many people consider XML not being source code but configuration. Hence, modifying XML is considered less risky or more convenient than changing a Java class.

A benefit of modifying the XML over modifying Java source is that you don't need to recompile your application; so those changes can be pushed easier in test/production without being involved in normal development activity (and testing). And this - in my personal view - is the worst part of the story.

I got answer on what are the good things on IoC, which is not what I asked. My intent is/was to understand why so many developers prefer having such XML files instead of relying on Java source to program the construction of objects.
Fortunately I see that this approach is on the way to be dismissed (or at least reduced), in favor of Spring annotations and/or other frameworks which are based on Java source code (like Guice that has been mentioned).

1
  • Should give you a vote for the summarization all the inputs u received. Above answer helps a lot for developers, who may hit here. May 26, 2017 at 4:43
0

Inversion of control or dependency injection will help you to control your dependency without touching your source codes. And you could do this in a XML

1
  • 1
    Why xml should not be considered source code?
    – Luigi
    Jan 8, 2013 at 17:20
0

The IOC xml instantiation provides modularity to your application. By using autowiring, you do not have to explicitly set the member variables/services within a class. Think of it this way many classes using 1..2..3..n services, may need several constructors or a factory class, or the worst approach getting and setting the services used by that class. By using Spring you can define that with in a class, and consumer of that class doesn't need to know or call a special method. You could define that bean component with an annotated notation and now just autowire it where necessary, no need to code factories.

As far as XML driven, I think hyness said it best, autowiring via annotations can greatly reduce the burden of maintaining an xml document, if you can upgrade your version of Spring.

0

Despite the fact that using XML files to configure your app could add more complexity by increasing the number of files you have to cater for. They do give you the advantage of keeping the code intact and avoiding changes for cases where you might wanna use a different Hibernate Dialect for instance and so on.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.