The main advantage is type safely that means JDK compiler can help to check whether we configure a bean's properties correctly at compile time (i.e set the properties with the correct name and correct data type).
It also means we can use IDE to easily refactoring the bean configuration (e.g. renaming a properties name etc.) and searching the bean usage.
For example, suppose we have the Car
and Engine
:
public class Car {
private Integer id;
private Engine engine;
}
public class Engine {
}
In Java based configuration below, we know that the Engine set into the Car must be in the Engine type and the Car's id must be an Integer. Otherwise, the code simply cannot compiled and IDE immediately give us warning (e.g You set a String to Car's ID due to mistake). We know the configuration is wrong without the need of bootstrapping the spring context.
@Configuration
public class AppConfig {
@Bean
public Engine engine(){
return new Engine();
}
public Car car(Engine engine){
Car car = new Car();
car.setId(12345);
car.setEngine(engine);
return engine;
}
}
When compared top the XML configuration, you can only know you configure the beans incorrectly after bootstrapping the spring context.