View RSS Feed

Spring Framework

Reduce your Spring XML using Java Configuration

Rate this Entry
by , 11-27-2011 at 09:47 PM (1313 Views)
As Spring has grown so has the need to configure more and more components leading to the xml configuration files growing larger and larger. In order to address this issue, the Java configuration project was started as a standalone project at SpringSource and developed over the years. It was finally integrated into the core Spring framework in version 3.0. Now you are able to use a powerful ApplicationContext configuration abstraction that has the same level of isolation as its XML cousin. In this way similar to when you use XML, it will not affect any of your code to use it! Your application can include APIs that you can use to modify with annotation decorations in your classes at will. So now most developers tend to configure these types of components with bean declarations, property editors, or custom schema definitions.

The simplest way to configure an application is to use a hybrid Spring XML and Java configuration. Simply create a vanilla XML configuration file enabled with component-scan from the context namespace and let Spring do the rest of the work. This allows you to continue using custom/bundled namespace elements or to include any unmanaged XML configuration metadata.

Java Code:
<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns=""
   <context:component-scan base-package="com.acme.springexamples.config.springexampleconfig"/>
Now you can build a a configuration class.

package com.acme.springexamples.config;

Java Code:
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import com.acme.springexamples.dao.HibernateOrderDaoImpl;
import com.acme.springexamples.dao.OrderDao;
import com.acme.springexamples.service.OrderService;
import com.acme.springexamples.service.OrderServiceImpl;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class SpringExampleConfig {

	public OrderService orderService(){
		return new OrderServiceImpl(orderDao());
	public OrderDao orderDao(){
		return new HibernateOrderDaoImpl(dataSource());
	public DataSource dataSource(){
		return new DriverManagerDataSource();
You use the @Configuration annotation serves to hold the Spring bean declarations. The bean declarations can then be made simple by just annotated with @Bean as shown above. This shows the use of the bean declaration method compared to the XML version. The key important benefit of this method is that it allows for compile time checking of the bean type and uniqueness of the beanís ID.

Submit "Reduce your Spring XML using Java Configuration" to Facebook Submit "Reduce your Spring XML using Java Configuration" to Digg Submit "Reduce your Spring XML using Java Configuration" to Submit "Reduce your Spring XML using Java Configuration" to StumbleUpon Submit "Reduce your Spring XML using Java Configuration" to Google