@Configuration is a Spring annotation that indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime, for example:
@Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } }
Here, the @Configuration
annotation indicates that the AppConfig
class contains one or more bean methods and the @Bean
annotation on the myService
method indicates that this method returns an object that should be registered as a bean in the Spring application context.
To use the @Configuration
annotation, you will need to have the Spring Framework on your classpath. If you are using Spring Boot, the Spring Framework is already included as a dependency, so you can use the @Configuration
annotation without any additional configuration.
To use the @Configuration
annotation in a Spring Boot application, you can follow these steps:
- Create a new Java class and annotate it with
@Configuration
. - Add
@Bean
methods to the class to define beans for the application context. - In your main application class, annotate it with
@EnableAutoConfiguration
or@SpringBootApplication
to enable Spring Boot’s auto-configuration features.
For example, consider the following AppConfig
class:
@Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } }
To use this configuration class in a Spring Boot application, you can create a main application class with the @EnableAutoConfiguration
or @SpringBootApplication
annotation, like this:
@EnableAutoConfiguration @Import(AppConfig.class) public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
Alternatively, you can use the @SpringBootApplication
annotation, which combines @Configuration
, @EnableAutoConfiguration
, and @ComponentScan
:
@SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
With either of these approaches, Spring Boot will scan for @Configuration
classes and use them to configure the application context. The @Bean
methods in these classes will be used to create and register beans with the application context.
You can also use the @Configuration
annotation in combination with @ComponentScan
to enable component scanning for your application. For example:
@Configuration @ComponentScan("com.example.myapp") public class AppConfig { ... }
This will cause Spring to scan the specified package, and its subpackages for classes annotated with @Component
or other Spring-specific annotations and register them as beans in the application context.
I hope this helps!
To learn more, check out the Spring Boot tutorials page.