Sobes.tech
Junior — Middle

How is the configuration and registration of a Bean carried out within the Spring Framework?

sobes.tech AI

Answer from AI

In Spring Framework, the configuration and registration of Beans (components) can be done in several ways:

  1. Annotations — the most common method. A class is marked with the @Component annotation (or specialized ones like @Service, @Repository), and Spring automatically scans packages and registers these classes as Beans.
@Component
public class MyService {
    // service logic
}
  1. Configuration classes with @Configuration and @Bean — in a class annotated with @Configuration, you can explicitly define methods that return Beans, marked with @Bean.
@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyService();
    }
}
  1. XML configuration — an outdated but still supported method, where Beans are described in an XML file.
<bean id="myService" class="com.example.MyService" />

After registration, the Spring container manages the Bean lifecycle and automatically injects dependencies if they are declared via constructor, setters, or fields with the @Autowired annotation.

How is the configuration and registration of a Bean… - sobes.tech