Understanding the @Configuration Annotation in Spring

The @Configuration annotation indicates to Spring that the class has one or more @Bean methods. When starting the application context, Spring will look to these classes to load the Spring IoC container with the beans you define in those methods.

It allows you to create custom beans and perform configurations (like when you use Spring Security) so that everything is ready to go when the application starts.

It’s a really simple and powerful annotation, often combined with other annotations.

Let’s see it in practice.

@Configuration It is a class-level annotation. So we can define a configuration class and create some bean methods like this:

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

@Configuration
public class MyConfiguration {

    private static final Logger log = LoggerFactory.getLogger(MyConfiguration.class);

    @Bean
    public MyBean myBean() {
        log.info("Creating my custom bean");
        return new MyBean();
    }
}

class MyBean {
    // bean properties and methods
}

@SpringBootApplication
public class Main {

    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

Spring will load your configurations by default if they’re in the same package as your application’s main. Or if it’s in the configurations, it’s in sub-packages from your application’s main.

For example:

If your main is in org.example.application And your configurations are located in packages in the same package tree, for example, org.example.application.config Spring will automatically scan and read these configurations for you.

But if it is not reading your configuration class because they are not in the same package tree, you could use the @Import annotation in your application, or use the @ComponentScan annotation to point to Spring, where those configurations are.

Now you know how to configure your Spring applications using the @Configuration annotation.

If you like this topic, make sure to follow me. In the following days, I’ll be explaining more about Spring annotations! Stay tuned!

Willian Moya (@WillianFMoya) / X (twitter.com)

Willian Ferreira Moya | LinkedIn


Posted

in

,

by