How many ways are there to configure the Spring framework? What are the differences between them technically? (Not pros or cons..)

To avoid confusion, we should understand, that configuration definition and bean definition are two different things. There are three ways to define configuration, available in Spring 4 by default:

  • xml-based configuration, when you describe configuration in xml file;
  • java-based configuration, when configuration is Java class, marked with specific annotations;
  • groovy-based configuration, when configuration is file with Groovy code;

And there are two ways to add bean definitions into application:

  • configuration inside bean definition, when you add beans manually by declaration right in configuration.

    In this case definition will be based on configuration type. For xml-config it will be <bean/> tag, for java-based config – method with @Bean annotation and beans {...} construction for Groovy.

  • annotation based bean definition, when you mark bean classes with specific annotations (like @Component, @Service, @Controller etc). This type of config uses classpath scanning.

In this case you have to specify directive for scanning classpath. For xml-config it will be <context:component-scan base-package="..."/>, for java-config – @ComponentScan annotation, for Groovy ctx.'component-scan'(...) invocation.

As you see, you can use configurations and bean definitions in different combinations.

Note, that if you use xml based config, you can choose approach to drive dependency injection: manually in xml, or by using annotations (@Autowire, @Required etc). In late case you have to define <context:annotation-config/>. But do not confuse bean definition and dependency injection control.

Now based on this point of view lets try to answer your questions:

Why is the (so-called) Annotation Based Configuration actually using
ClassPathXmlApplicationContext but not
AnnotationConfigApplicationContext above?

Book’s author mixed up concepts. Actually, this is a xml-based configuration with annotation-based bean definition.

The Java Based Configuration explained in the book seems like what
should be called Annotation Based Configuration.?

You’re right – Java based configuration really actively uses annotations, and could be called Annotation based. But annotation is a part of Java. In addition this is a traditional term, specified in documentation.

How many ways are there to configure Spring framework?

So, by default, we have three ways to describe configuration, and two ways to define beans. That turns six ways to configure Spring framework(by default). But, of course, all of this ways can be used in combination with each other.

Leave a Comment