Explaining @PostConstruct & Factory Pattern in Java Spring

May 28, 2022

Here’s a short video that explains how @PostConstruct works in Spring and how to pair it with a factory pattern.

📺 Watch the video


🧠 Reference


📝 Transcript

This is going to be a quick example on how @PostConstruct works and how you can use it in your projects.

First off, we have here a basic application which runs a Spring application. This is going to use @PostConstruct and show you where you can customize your logic. Let’s go ahead and add a debugger right here and I’m going to run my application.

We can see here the debugger stops—we can look in the console log to see what’s happening. Right here we can initialize our own custom logic. This occurs before the application even runs. You can see that @PostConstruct runs right after the initialization of the JPA EntityManagerFactory. We can use this to essentially autowire or inject dependencies.

We’ll continue running this and put a debugger at the end of the application run—you can see the application has finished running. Now let’s look at more practical examples of how to use @PostConstruct.

This is an example I picked up from Stack Overflow (linked above). We have a list of a Factory interface. Essentially, this is going to get a list of anything that implements the Factory interface—so in our case FactoryOne and FactoryTwo implement the Factory interface.

We’ll get a list of these factory implementations, and then with our @PostConstruct method we initialize a factory cache (e.g., Map<Key, Factory>). This will allow us to later retrieve a factory by key.

Let’s see this in action. We place a debugger to verify what’s going on and run the test. Just like before, @PostConstruct runs right after initialization and before the app runs. We see that it indeed has a list of our factories that implement the interface.

Now this loop builds the cache so we can retrieve by key:

  • Put the key,
  • Put the implementation instance as the value,
  • Loop until every factory is registered.

Back in the test, we create a new FactoryPicker, then retrieve a factory by key—and there you go.

If you like this video, please give it a thumbs up and subscribe. If you want a specific video request, comment below—thanks for watching!