You can configure a Spring application entirely using xml configuration or using a Java configuration. XML configuration was the original configuration approach in Spring. Spring 2.0, which came in 2006, simplified the XML configurations.Spring 2.5, which came in 2007, introduced annotation configurations. Spring 3.2, which came in 2012, introduced Java configuration. You can use annotations to do most of the things along with xml or java configuration. However, you will mostly not see both xml configuration or Java configuration used together.
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.
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)
Please refer to below examples for these different approaches. You can read about in below link or wait until it is discussed as part of this series of notes.
Searches whole web. Use the search in the right sidebar to search only within javajee.com!!!