Spring DI with the factory method

So far, we have seen that the Spring container takes care of creating the instances of bean. In some scenarios, you need to take control of creating an instance of bean with custom code. Spring supports this feature with the help of the factory method.

You can write your custom logic to create the instance in the factory method, and just instruct Spring to use it. When Spring encounters such instructions, it will call the factory method to create the instance. So, the factory method is kind of a callback function. 

There are two flavors of the factory method: static, and instance (non-static).

Get Java 9 Dependency Injection now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.