JavaConfig in Spring 3.0

Spring 3.0 has introduced new way for configuring the spring beans. In fact this was maintained by spring framework separately as JavaConfig. Later it is merged to the spring core framework and all the features are directly accessible from the spring core. Instead of using the XML files, we can use plain Java classes to annotate the configurations by using the @Configuration annotation. If you annotate a class with @Configuration annotation, it indicates that the class is used for defining the beans using the @Bean annotation. This is very much similar to the <bean/> element in the spring XML configurations.

This approach is not 100% replacement for the XML configurations. It is upto the developer’s choice to choose between JavaConfig and XML configurations. In most cases, the bootstrap configuration will be done using the XML file and then JavaConfig will be used for adhoc requirements.

Also read:

The following are the list of annotations introduced as part of the JavaConfig project.

  1. @Configuration
  2. @Bean
  3. @DependsOn
  4. @Primary
  5. @Lazy
  6. @Import
  7. @ImportResource
  8. @Value

In this example I have used only the first two annotations to demonstrate the basic use of JavaConfig features.

AnnotationConfigApplicationContext is the class used for loading the configuration from Java class file. Look at the below example. If you have any questions, please write it in the comments section.

1. Create JavaConfig

  • Annotate the class with @Configuration annotation
  • Annotate the method with @Bean to indicating that it is bean definition

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

public class JavaConfig {
	public UserDetails userDetails(){
		return new UserDetails();

2. Create Bean Class


public class UserDetails {
	private String name;
	private String phone;
	private String city;
	private String country;

        // Other methods


3. Load Application Context and Instantiate Bean

Create AnnotationConfigApplicationContext and get the bean instance. This is very simple example to show you how simple to configure the beans using Java class.


import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class JavaConfigDemo {
	public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
        UserDetails userDetails = (UserDetails) context.getBean("userDetails");

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!