Skip to content
Advertisement

Is it necessary to use @Configuration while working with spring annotations

I am working with a simple spring application to check @Configuration and @Bean(java based configuartion only),The program is working with both @Configuration and without it.So is it necessary to have it.

Here is my code,

Student.java

JavaScript

Faculty.java

JavaScript

MyConfig.java

JavaScript

Client.java

JavaScript

The output is same with or without the @Configuration

JavaScript

Even tried with autowiring,it is also working without @Configuration

Student.java

JavaScript

Client.java

JavaScript

Advertisement

Answer

When using Java based configuration with Spring you basically have 2 options (as you already noticed). You have the option to annotate a class with @Configuration and have all the @Bean annotated methods available as beans. However you can also do this without the @Configuration annotation. The latter is called the so called lite mode.

When using @Configuration classes the beans defined in there are regular Spring beans and when calling one method from another this will always result in the same instance of a bean. Spring detects the @Configuration classes and treats them in a very special way (it will create a proxy for those classes).

When using lite-mode the @Bean methods are basically nothing more than factory methods, although they participate in (part of) the lifecycle of Spring Beans. When calling them each call will get you a new bean. Which means that, inter bean dependencies, will get you new instances each time the method gets called.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement