I recently came across a problem when migrating an old java code base to use the Spring framework. More specific we needed to implement spring-data-mongo and took the opportunity to “springify” the application properly.
The app is using quite a few abstract classes, sometimes a couple of levels deep and as an example the top level abstract class did contain code to read from properties files and also did have some class level members that needed to instantiated.
Class structure
TopLevelClass (abstract)
- Reading info from properties file
- Member needing to instantiated
MidLevelClass (abstract, implementing TopLevelClass)
- Some common code
InstanceClass (implementing MidLevelClass)
- Not much code, just specific for the instance.
Reading properties
To make this work we needed to get our heads around how Spring scans the code. Abstract classes are not scanned and this means that we needed to move the property handling to the InstanceClass (using @PropertySource and Environment autowired).
Autowiring
The second issue was a bit trickier and https://www.baeldung.com/spring-autowired-abstract-class came to rescue. To be able to instantiate the member in TopLevelClass you need to autowire a constructor in InstanceClass that calls super(member) that propagates up to TopLevelClass. Then all code will be instantiated properly even in the abstract classes.
Code examples is coming up!