Traditionally Spring applications were configured using only xml configurations. Later annotations such as @Component came and complemented the xml configuration. However later XML configurations were completely replaced by Java configurations that use annotations such as @Bean.
In xml configuration, you use xml to configure beans.
We can load an xml configuration file from a standalone application as:
ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml");
Though annotations and Java configuration are the preferred approaches, xml configurations might be handy in cases such as:
We do not have access to the classes to write access annotations.
Some libraries (or some versions) might not support Java configurations completely.
Some features might be significantly more difficult to do in Java configuration than on XML due to various shortcuts and features available with XML configurations.
Xml configuration is not supported much these days, but are supported for backward compatibility. You can find examples here.
Annotations can be used along with xml configuration or java configuration. When using annotations, @Component is the most important annotation that specifies that the class needs to be considered as a bean. You also needs to specify the paths on which Spring should look for such components either using @ComponentScan annotation or the <context:component-scan tag in the xml configuration file.
There are also other component annotations that gives more clarity about the purpose of the bean. You can read about in below link or wait until it is discussed as part of this series of notes.
In Java configuration, you can have a java class file annotated with @Configuration to create and manage beans.
We can load a Java configuration file from a standalone application as:
ApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class);
Inside a Java configuration file, you can import other Java configuration files using @Import and can even import other xml based configuration files using @ImportResource.
Java configuration is the most preferred approach in newer projects as:
You can keep your configurations at one centralized place (when compared to a complete annotations approach)
We can make use of Java compiler to make sure that we are doing right thing (compared to xml approach)
We can use any of the Java language features to write any kind of (even complex) bean configurations (compared to xml approach)
Searches whole web. Use the search in the right sidebar to search only within javajee.com!!!