-1

I suppose someone should have asked this question given it's been long time since spring has introduced java based config. But as no such result are showing up on SOF, I am take this further.

Are there any advantages with Java based configuration over XML based configuration?

(On the contrary, i can see one advantage with XML config. XML Config can be changed post compilation based on environment the application is being deployed to - like staging, test or production. This I see will not be possible with java config )

samshers
  • 1
  • 6
  • 37
  • 84

1 Answers1

0

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.

Monolith
  • 1,067
  • 1
  • 13
  • 29
Ken Chan
  • 84,777
  • 26
  • 143
  • 172