Spring
June 6, 2020

M01 Q20 What are the advantages of Java Config? What are the limitations?

Advantages of Java Config over XML Config

1. Compile-Time Feedback due to Type-checking

Let's say that we can make a mistake during configuration. For example, mismatch the type. And if you try to compile this code you will see that compiler throws an error. Because it sees that types are incompatible.

So instead of finding out on the runtime after the compilation and after executing the project that something is wrong, I can find the issue in the process.

When you use XML-file configuration compiler doesn't know that you mismatch the type. Because XML-file is a regular file on the classpath. Code with type mismatch will compile but you will get the UnsatisfiedDependencyException on runtime.

One way you get to know about type mismatch in XML-file is when you are using IntelliJ IDEA Ultimate and you installed Spring plugin.

2. Refactoring Tools for Java without special support/plugins work out of the box with Java Config (special support needed for XML Config)

Let's imagine that during refactoring you move one of the beans to a different package. In this case, IDE doesn't modify your XML-file and you can forget to change the bean path in XML-file. Code will compile correctly but at runtime, it will fail with ClassNotfoundException.

Except, Ultimate IntelliJ IDEA with Spring extension can automatically detect path changing.

Advantages of Java Config over Annotation Based Config

1. Separation of concerns – beans configuration is separated from beans implementation. That means only configuration class know about beans. And each of the bean implementations does not have any information that is a component, what is the scope and etc. All of this information is in configuration class.

2. Technology agnostic – beans may not depend on concrete IoC/DI implementation – makes it easier to switch technology. That's because any of the beans have not dependency directly on the Spring framework.

3. Ability to integrate Spring with external libraries. Any class of the eternal library can be a Bean. Simply create a method with @Bean annotation that returns a new object.

4. The more centralized location of bean list

Limitations of Java Config

1. Configuration class cannot be final

2. Configuration class methods cannot be final

3. All Beans have to be listed, for big applications, it might be a challenge compared to Component Scanning

The reason that you cannot create a final configuration class or method is that under the hood it will not work with configuration class directly. Instead, the CGLIB Proxy will be created.

Spring does this because if we have a default scope - a singleton. And it will not create bean several times. We want to have only one instance. And this is why proxy will be used to guard behaviour that it can be invoked only once. And also as you know, CGLIB cannot work with final classes and methods.