Junior — Middle
How can automatic bean creation be configured in Spring?
sobes.tech AI
Answer from AI
In Spring, automatic bean creation can be configured using annotations and component scanning.
Main steps:
- Annotate classes that should become beans with annotations such as
@Component,@Service,@Repository, or@Controller. - Enable package scanning in Spring configuration using
@ComponentScan.
Example:
@Configuration
@ComponentScan(basePackages = "com.example.myapp")
public class AppConfig {
}
@Component
public class MyService {
// service logic
}
When Spring starts, it will automatically find the MyService class and create its bean, which can be injected using @Autowired.
This avoids manual bean definitions in XML or Java configuration and simplifies dependency management.