Spring
June 6, 2020

M01 Q23 Why are you not allowed to annotate a final class with @Configuration?

Why are you not allowed to annotate a final class with @Configuration? Why can’t @Bean methods be final either?

A class annotated with @Configuration cannot be final because Spring will use CGLIB to create a proxy for @Configuration class. CGLIB creates subclass for each class that is supposed to be proxied, however since the final class cannot have subclass CGLIB will fail. This is also a reason why methods cannot be final, Spring needs to override methods from parent class for the proxy to work correctly, however, final method cannot be overridden, having such a method will make CGLIB fail.

If @Configuration class will be final or will have a final method, Spring will throw BeanDefinitionParsingException.

How do @Configuration annotated classes support singleton beans?

Spring supports Singleton beans in @Configuration class by creating a CGLIB proxy that intercepts calls to the method. Before a method is executed from the proxied class, proxy intercepts a call and checks if the instance of the bean already exists

  • If the instance of the bean exists, then call to the method is not allowed and the already existing instance is returned
  • If the instance does not exist, then call is allowed, the bean is created and the instance is returned and saved for future reuse.

To make a method call interception CGLIB proxy needs to create a subclass and also needs to override methods.

The easiest way to observe that calls to original @Configuration class are proxied is with the usage of a debugger or by printing stack trace. When looking at stack trace you will notice that class which serves beans is not original class written by you but it is a different class, which name contains $EnhancerBySpringCGLIB.