Scan classes with conditions by using the Spring framework

When we developed the front-end of MyCollab product, we need to keep the view classes are independent of the business classes and MyCollab must detect the view classes at runtime. For instance, we have three implementations of Billing pages:

  • Open source edition: the billing page simply is useless. We just say hello and wish users enjoy our Open source product
  • Ultimate edition:  the billing page tell the users when the license is expired, how many allowed users in their package etc
  • Cloud edition: we list all subscription plans, allow user can upgrade or downgrade their plan etc

We do not want to put all three implementations of Billing page in the one package and select the right class to load at the run-time because the users can read the close source of paid version or the distribution files becomes larger. One solution is putting each of implementation to the right jar file, and scan classes to load the right one implementation of the interface. At the beginning, we use Reflections but it is not stable enough (However, it may become better at the time of writing) when the scan performance does in the unpredict order. While Spring also scans its service beans during run-time so we think it is a waste if we used another toolkit to scan the classpaths again.

To configure Spring to scan your classes is simple. Firstly, you define a ClassPathScanningCandidateComponentProvider and its filter

then we limit the scanning process in the selected package

Finally, we have two sets of classes satisfy our selection criteria by scanning all classes in the classpaths. With the Spring framework 4, the scanning process is very fast and the speed is predictable across machines. If you are using Spring, you should not rely any other toolkit to scan your classes though there is a long list of libraries to do so.

You can read the full source code at Github.

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *