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:
- Annotations — the most common method. A class is marked with the
@Componentannotation (or specialized ones like@Service,@Repository), and Spring automatically scans packages and registers these classes as Beans.
@Component
public class MyService {
// service logic
}
- Configuration classes with
@Configurationand@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();
}
}
- 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.