@Configuration annotation example using spring boot

In this post, we will see the @Configuration annotation example using spring boot. In Spring Framework, the @Configuration annotation is used to declare a class as a configuration class. Configuration classes are a way to define Spring beans and their dependencies using Java-based configuration instead of XML-based configuration. This annotation is often used in conjunction with other annotations like @Bean, @ComponentScan, and @Import to configure Spring applications.

XML-based approach

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <!-- bean definition -->
   <bean id = "mybeanexample1" class = "com.somepackage">
   </bean>
</bean>

Using @Configuration annotation

Suppose we have a class ApplicationConfig.java where we have configuration related stuff. For example, creating datasource or we want to define different beans.

@Configuration
public class ApplicationConfig {
        @Bean
	public ExampleBean getExampleBean()  {
		return new ExampleBean();
   }
}

Some more examples that demonstrate how to use @Configuration annotation

Here’s how the @Configuration annotation works:

  1. Declaration: You annotate a Java class with @Configuration to indicate that it contains Spring bean definitions.
  2. Bean Definitions: Inside the configuration class, you define Spring beans using the @Bean annotation on methods. These methods return instances of the beans you want to configure.
   @Configuration
   public class MyAppConfig {
       @Bean
       public MyService myService() {
           return new MyServiceImpl();
       }
   }

In this example, the myService method is annotated with @Bean, which tells Spring to create a bean of type MyService and manage its lifecycle.

  1. Component Scanning: You can also combine @Configuration with @ComponentScan to automatically discover and register Spring beans from specified packages.
   @Configuration
   @ComponentScan(basePackages = "com.example.myapp")
   public class AppConfig {
   }

With this configuration, Spring will scan the com.example.myapp package for classes annotated with @Component, @Service, @Repository, etc., and register them as beans.

  1. Importing Configurations: You can import other configuration classes using the @Import annotation, allowing you to modularize your configuration.
   @Configuration
   @Import(DatabaseConfig.class)
   public class AppConfig {
   }

Here, the DatabaseConfig class is imported into the AppConfig configuration class.

  1. Property Configuration: You can also use @PropertySource and @Value annotations within @Configuration classes to externalize configuration properties.
   @Configuration
   @PropertySource("classpath:application.properties")
   public class AppConfig {

       @Value("${myapp.db.url}")
       private String dbUrl;

       // ...
   }

The @Configuration annotation is a fundamental building block of Spring applications, enabling you to define and manage beans, wire dependencies, and configure various aspects of your application through Java-based code.

Let’s see some real time scenario where you can use @Configure annotation.

Suppose we want to configure WebMvcConfiureAdapter. This is a predefined class(available in org.springframework.web.servlet.config.annotation package) can be used for content negotiation. Here content negotiation means what type of data we want to produce as the response. We can configure using @Configuration annotation and then we need to override some method. Let’s see an example.

package com.bootwar.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebAppAdapterConfiguration extends WebMvcConfigurerAdapter{
	@Override
	public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
		
		configurer.defaultContentType(MediaType.APPLICATION_XML);
		// We can configure what kind of data we want to show
		//configurer.defaultContentType(MediaType.APPLICATION_JSON);
		//configurer.defaultContentType(MediaType.APPLICATION_FORM_URLENCODED);
	}

}

Similarly, we can configure formatters and resourcehandlers and other stuff.

        @Override
	public void addFormatters(FormatterRegistry registry) {
        //Some more logic
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
         //Some more logic
	}

	
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //Some more logic
	}

Note – WebMvcConfiureAdapter class has been deprecated now.

Summary – @Configuration annotation is used to configure the different resources(Earlier we suppose to do the same task using XML ). Some common scenario where we used this annotation, use this annotation with class and create bean using @Bean annotation(for example – creating datasource bean, entityManagerBean, transactionManager and many more). Also, we can configure ContentNegotiation, Formatters, interceptors etc. While using @Configuration annotation it is good practice to define a separate class for different configuration purposes.

An example which shows how to use @Configuration annotation and create bean using @Bean annotation.

Five objective questions related to Spring @Configuration.The answers are provided at the end.

Question 1: What is the purpose of the @Configuration annotation in a Spring application?

A) To define a Spring bean’s properties.
B) To specify the location of XML configuration files.
C) To indicate that a class contains bean definitions and configuration.
D) To enable automatic component scanning.

Question 2: Which annotation is used in conjunction with @Configuration to define individual Spring beans in a configuration class?

A) @Component
B) @Bean
C) @Autowired
D) @Service

Question 3: What does the @ComponentScan annotation do when used within a @Configuration class?

A) It imports other configuration classes.
B) It defines the properties of Spring beans.
C) It specifies the base package for component scanning.
D) It enables AOP (Aspect-Oriented Programming).

Question 4: Which of the following statements is true regarding @Configuration classes in Spring?

A) @Configuration classes cannot be imported into other configuration classes.
B) You can define Spring beans using @Bean methods only in XML configuration files.
C) @Configuration classes are used to configure Spring applications using Java-based code.
D) @Configuration classes can only be used for testing purposes.

Question 5: How can external properties be loaded and used within a @Configuration class in Spring?

A) By defining properties using @Value annotations within the class.
B) By using @ConfigurationProperties on a class field.
C) By importing a properties file using @PropertySource.
D) By directly defining properties in the @Configuration class itself.

Answers:

1) C) To indicate that a class contains bean definitions and configuration.

2) B) @Bean

3) C) It specifies the base package for component scanning.

4) C) @Configuration classes are used to configure Spring applications using Java-based code.

5) C) By importing a properties file using @PropertySource.

That’s all about @Configuration annotation example using spring boot. You may like.

Check @Configuration annotation docs here.