Sobes.tech
Junior — Middle

Explain the working mechanism of the Factory Method pattern in the context of Spring Framework.

sobes.tech AI

Answer from AI

In the Spring Framework, the Factory Method pattern is implemented through the use of factory methods for creating beans. Instead of directly creating objects via constructors, Spring allows you to define a factory method responsible for creating instances.

How it works:

  • In Spring configuration (XML or Java-based), a method is specified that will create the object.
  • When the bean is requested, Spring calls this method to obtain the ready object.
  • This allows encapsulating creation logic, such as selecting a specific implementation of an interface based on conditions.

Example in Java configuration:

@Configuration
public class AppConfig {
    @Bean
    public Service service() {
        return ServiceFactory.createService();
    }
}

Here, ServiceFactory.createService() is the factory method that creates a Service object. This approach simplifies replacing implementations and managing object lifecycle.