Building Microservices with Spring
上QQ阅读APP看书,第一时间看更新

Implementing the Abstract factory design pattern in the Spring Framework

In the Spring Framework, the FactoryBean interface is based on the Abstract Factory design pattern. Spring provides a lot of implementation of this interface, such as ProxyFactoryBean, JndiFactoryBean, LocalSessionFactoryBean, LocalContainerEntityManagerFactoryBean, and so on. A FactoryBean is also useful to help Spring construct objects that it couldn't easily construct itself. Often this is used to construct complex objects that have many dependencies. It might also be used when the construction logic itself is highly volatile and depends on the configuration.

For example, in Spring Framework, one of the FactoryBean implementations is LocalSessionFactoryBean, which is used to get a reference of a bean that was associated with the hibernate configuration. It is a specific configuration concerning the data source. It should be applied before you get an object of SessionFactory. You can use the LocalSessionFactoryBean to apply the specific data source configuration in a consistent way. You may inject the result of a FactoryBean's getObject() method into any other property.

Let's create a sample implementation of the Abstract Factory design pattern.