Junior — Middle
What alternative methods, besides using XML or annotations, can be used to implement bean creation in Spring?
sobes.tech AI
Answer from AI
In addition to using XML configuration and annotations, Spring allows creating beans through the following alternative methods:
- Java-based configuration (Java Config) — creating beans using classes annotated with
@Configurationand methods annotated with@Bean.
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
-
Programmatic creation and registration of beans via BeanDefinitionRegistry — beans can be registered programmatically in the context using Spring's API.
-
FactoryBean — creating a bean through the implementation of the
FactoryBeaninterface, which manages object creation. -
Using ApplicationContext programmatically — beans can be created and registered dynamically at runtime.
Thus, Java Config is the most modern and convenient method, often replacing XML, while programmatic registration and FactoryBean provide additional control over bean creation.