Saturday, September 1, 2012

What is Cross Cutting Concerns in Spring?

The majority of application we design will contain common functionality that spans across tiers and layers, such as Security, Caching, Logging, Transactions and more. These are called crosscutting concerns. "Concern" means logic/functionality. Since it affects the entire application, and should have been in one centralised location rather than scattered across application layers and tiers.

For example: You have application, which spans multiple layers say Controller, Service and DAO. You have a requirement to add the logging code to one of the DAO method, yes that's easy one, just go to that method, and add the logging code at the top of the method, then there is a requirement to add Security code to the same method, where you have added the logging, yes this also seems to easy, you just go to the method, and add the necessary security logic to the method after the logging. Now you got a requirement to extend this logic to all the layers(Controllers and Service) of that method, okay little tedious, but we are expert in copy and paste, we will copy the code from the DAO and paste it in Service and Controller, that's all done. But really what we have done is a dirty job.

Now, if they want this to be done in our entire system, little crazy now, already we have done a dirty job by doing a copy paste of DAO to Service and Controller, our code has been scattered, if we need to change, we have to update all the classes, it will not be a big deal if it is one or two classes, but for entire application it is a pain full job.

That's where we will be using the Aspect Oriented Programming (AOP) . It is a programming technique based on the concept of an Aspect. Aspect encapsulates cross-cutting logic, the basic infrastructure code which all application needs. What we are going to do is, we will take the logging and security code, and encapsulate it into a module for a reusable code.

Will soon publish a post on how to configure the AOP in Spring along with the Cross Cutting Concerns

Happy Programming ...!!!