Rahul Agrawal
Rahul Agrawal

Reputation: 8971

What is difference between these 2 Spring Annotation and XML config

What is difference between these 2 Spring Annotation and XML config

1) Annotation Based

@Configuration
@EnableWebMvc
public class MyWebConfig{
   // 
}

2) XML Based

<mvc:annotation-driven />

I can not see any other difference than xml and annotation. and When to use which one ?

Upvotes: 0

Views: 2754

Answers (2)

Grzegorz Rożniecki
Grzegorz Rożniecki

Reputation: 28045

@Treydone wrote some examples plus expressed subjective opinion about Java based config being better.

I disagree with this statement, because there is no functional difference between Java based configuration and XML configuration, it's only matter of habit which one will you use. Some say traditional XML namespace config is better, others say Java based configuration (which is in Spring since 3.0) is the next level of IoC in Spring.

BTW Annotation based configuration is not the same as Java based one - you wrote example from the latter, so I assume you are choosing between XML and Java configs.

I think you should read:

and then decide which one is the best for you.

P.S. Annotation based configuration is IMO worse choice than these two as it moves some depedency information directly into ordinary classes.

Upvotes: 1

Vincent Devillers
Vincent Devillers

Reputation: 1628

Annotations based configuration is easier and more readable to build than the equivalent in xml. For instance setting a property as map in xml looks like this:

    <property name="maps">
        <map>
            <entry key="Key 1" value="1" />
            <entry key="Key 2" value-ref="PersonBean" />
            <entry key="Key 3">
                <bean class="com.mkyong.common.Person">
                    <property name="name" value="mkyongMap" />
                    <property name="address" value="address" />
                    <property name="age" value="28" />
                </bean>
            </entry>
        </map>
    </property>

In a java configuration file, this looks like this:

Map<String, Object> maps = ...
maps.put()...
....setMaps(maps);

There are many others pros:

  • Add a bean from an instance of an anonymous inner type

  • See the errors during the compilation, before starting your Spring context and your tomcat...

  • Add some conditions in your bean construction

For instance:

@Bean
public ViewResolver internalResourceViewResolver() {
    ClassLoader classLoader = getClass().getClassLoader();
    if (ClassUtils.isPresent("org.apache.tiles.TilesContainer", classLoader)) {
        TilesViewResolver viewResolver = new TilesViewResolver();
        return viewResolver;
    } else {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/");
        viewResolver.setSuffix(".jsp");         
        return viewResolver;
    }
}
  • Many others....

Upvotes: 1

Related Questions