Junior — Middle
What are the main steps and requirements for configuring and registering beans in the context of dependency injection?
sobes.tech AI
Answer from AI
To configure and register beans in a dependency injection context (for example, in the Spring Framework), the following steps are usually performed:
-
Define the bean class — create a class that will be managed by the container.
-
Annotation or configuration:
- Use annotations, such as
@Component,@Service,@Repository, for automatic scanning and registration. - Or explicitly declare the bean in a configuration class using
@Bean.
- Use annotations, such as
-
Configure dependencies — via constructor, setters, or fields with the
@Autowiredannotation. -
Register in the container — the IoC container automatically creates and manages the bean lifecycle.
Example using annotations:
@Component
public class MyService {
// dependencies
@Autowired
private MyRepository repository;
// methods
}
Or through configuration:
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService(myRepository());
}
@Bean
public MyRepository myRepository() {
return new MyRepository();
}
}
Main requirements:
- Classes should be available for scanning or explicitly declared.
- Dependencies should be correctly defined and accessible.
- The container should be configured to manage the bean lifecycle.