How to Build Apps with Spring AOP

How to Build Apps with Spring AOP

Check out this tutorial where we take a closer look at real-world applications of AOP concepts to Spring projects.

Spring AOP gives us a cleaner approach to write code. It helps in segregating business logic and cross-cutting stuff. Some of the cross-cutting stuff are logging, security management, transaction management, etc.

By using AOP, we could also add more functionality to methods in a class, even though the source code is not available.

Here, we are not going to discuss the basics of AOP. The expectation is that readers are well aware of the basic concepts of AOP like advice, aspect, pointcut, etc. We will focus mainly on Spring AOP applications.

In any application that we develop, we define business logic in the business layer, and to execute the business logic, the business layer collaborates with the repository/data access layer. And then, the repository layer interacts with the database for any data.

A typical example of business logic and repository layer are as follows:

@Component
public class BusinessLogic {
 @Autowired
 Repository Config repositoryConfig;
 @Autowired
 Repository A repositoryA;
 public void write(Repository repository) {

 switch (repository) {

  case REPOSITORYA:

  repositoryConfig.writeToCollectionA();

  break;

  caseREPOSITORYB:

   repositoryA.writeToCollectionB();

  break;

 }

 }

 public void read(Repository repository) {

 switch (repository) {

  caseREPOSITORYA:

  repositoryConfig.readFromCollectionA();

  break;

  caseREPOSITORYB:

  repositoryA.readFromCollectionB();

  break;

 }

 }
}

@Component

public class RepositoryA {

 public void readFromCollectionB() {

 System.out.println("Reading from collectionA");

 }

 public void writeToCollectionB() {

 System.out.println("Writing to collectionA");

 }

}

@Component

public class RepositoryConfig {

 public void readFromCollectionA() {

 System.out.println("Reading from collection Config");

 }

 public void writeToCollectionA() {

 System.out.println("Writing to collection Config");

 }

}

In the above example, we have a BusinessLogic class in the Business Layer, and it interacts with two Repository Layer classes: RepositoryA and RepositoryConfig.

In our Repositories classes, we have added a dummy implementation, but in the real world, we will write code to interact with the database.

Let’s assume the following scenario.

In the first release of our application, we didn't have the authorization functionality, but in the subsequent release, we have added authorization functionality. Now, we have a change request that only admin users should be allowed to read or write from the configuration collection.

In our above example, the RepositoryConfig class interacts with the Configuration collection. So, now, we need to add a check if the user is admin before it queries the Configuration collection.

One way to implement this functionality is to create an Authorization class and isAuthorized method to check whether the user is authorized or not. We update all the methods of RepositoryConfig and check authorization by calling isAuthorized method.

@Component

public class RepositoryConfig {

public void readFromCollectionA() {

if (Authorization.isAuthorised(Session.getUserId())) {

System.out.println("Reading from collectionA");

}

}

public void writeToCollectionA() {

if (Authorization.isAuthorised(Session.getUserId())) {

System.out.println("Writing to collectionA");

}

}

}

However, there is a disadvantage to this approach. We need to modify each and every method of RepositoryConfig class and the same code of calling the isAuthorized method is repeated across all the methods to check the authorization.

It will be good if without changing the existing class, we can add the authorization check functionality.

Let’s see how we can leverage the power of AOP to achieve this.

We will define an AuthorizationCheck class where we mention the aspect. We create a pointcut to the RepositoryConfig class and advice type is around. In the advice, we check if the user is admin, then we proceed; otherwise, we don’t.

There is no need to make any changes in the RepositoryConfig class. 

The code is mentioned below.

@Aspect

@Configuration

public class AuthorizationCheck {

 @Around("execution(** com.springboot.tutorial.aop.repository.RepositoryConfig.*(..))")

 public void check (ProceedingJoinPoint jp) {

      try {

           if(Authorization.isAuthorised(Session.getUserId())) {

                 jp.proceed();

           }

           else {

                 System.out.println("User not Authorised");

           }

      } catch (Throwable e) {

                e.printStackTrace();

      }

 }

}

Now, for any call to any of the methods of the RepositoryConfig class, this aspect will get called first, only if the condition satisfies the actual method will get called.

As you see above, without changing the existing class, we have added functionality. Using the same concept, we can even extend the functionality when we don’t have the source code.

Another useful application of AOP is that we can add functionality in a controlled manner with help of annotations.

Let’s consider a scenario where we are investigating a performance issue, and for that, we randomly check the turnaround time of a method.

AOP combined with annotations can make things very simple. Let’s create a custom annotation TurnAroundTime and apply it to the methods on which we want to check the performance.

Below is an example:

First, we need to create an annotation.

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

[email protected] TurnAroundTime {

}

We want to check the performance of a method, so here, the target type is Method. RetentionPolicy is runtime, as we want to apply during run time.

Next, we define the aspect.

@Aspect

@Configuration

public class PerformanceCheck {

@Around("execution(** com.springboot.tutorial.aop...*(..)) &&

@annotation(TurnAroundTime)")

public void watchPerformance(ProceedingJoinPoint jp) {

Instant start = Instant.now();

try {

jp.proceed();

} catch (Throwable e) {

e.printStackTrace();

}

Instant finish = Instant.now();

long timeElapsed = Duration.between(start, finish).toMillis();

System.out.println("Total Turnaround time:" + timeElapsed);

}

}

We define an aspect with pointcut as our custom annotation and advice type is around. We measure the difference between the time before the method execution begins and after the control returns and log the difference.

So, whenever we want to measure the performance, we need to annotate the method with the custom annotation @TurnAroundTime.

Something like this:

@Component

public class BusinessLogic {

@Autowired

 RepositoryConfig repositoryConfig;

@Autowired

 RepositoryA repositoryA;



 @TurnAroundTime

 public void write(Repository repository) {

      switch(repository){

      caseREPOSITORYA:

           repositoryConfig.writeToCollectionA();

           break;

      caseREPOSITORYB:

           repositoryA.writeToCollectionB();

           break;


                
      }

 }

}

The turnaround time of the method will be logged.

As we see, there are a few disadvantages using Spring AOP. If a new developer joins the team and he/she is not well versed with Spring AOP, sometimes, it becomes a bit confusing to debug. It is recommended to have good documentation practice.

Thanks for reading! Originally published on https://dzone.com

ECommerce Mobile App Development | Ecommerce Mobile App Development Services

We are leading ecommerce mobile application development company. Hire our ecommerce mobile app developer for your custom Ecommerce project at competitive rates. **Know about [Top ECommerce Mobile App Development...

We are leading ecommerce mobile application development company. Hire our ecommerce mobile app developer for your custom Ecommerce project at competitive rates.

Know about Top ECommerce Mobile App Development Company

Is Low-code or no-code development is future of mobile app development

Is Low-code or no-code development is future of mobile app development

Mobile app development has skyrocketed over these years with the increasing demand of mobile apps for a variety of purposes like entertainment, banking, weather update, health, booking movie tickets, booking a taxi etc. With the latest...

Mobile app development has skyrocketed over these years with the increasing demand of mobile apps for a variety of purposes like entertainment, banking, weather update, health, booking movie tickets, booking a taxi etc. With the latest technologies adopted by mobile app development services, there are different app development approaches which are being practiced. Among them is low-code or no-code development. But will it be the future of mobile app development? Will any mobile application development company start taking this approach as the primary one. Let’s try to find a detailed answer to this question.

But first, let’s understand what this approach exactly is? Well, it is a streamlined approach which involves swift design as well as development with minimal coding, generally relying on different third-party APIs.

Even though there isn’t any single definition of no-code or low-code development because it is actually more of a mindset rather than something which can be directly measured, this mindset has certainly led to a vast community mushrooming up with this mentality. Android app development services are rapidly adopted by this approach. Low-code app innovators are rapidly disrupting all types of various industries. There are a plethora of benefits to these low code platforms and let’s look at this.

1. Less Number of Bugs

It is pretty evident that less code actually means fewer bugs. As simple as that. The entire bug testing phase is actually a major part of modern and latest application development. It is quite inevitable that various issues will come up if there is actually enough code present there. But the best thing regarding low code platforms is that there’s certainly less to test. Also, when they actually tap into APIs, those particular APIs are actually tested by other people.

Lesser number of bugs is better for both users, as well as developers since less amount of time, will be taken up with bug-fixes and troubleshooting. Also, the fast pace of this development approach actually means that if in any case a bug is found, it is generally better just to develop a new iteration rather than fixing it.

2. Significant Lower Costs

Among the most obvious reasons for why you would actually opt for any low code platform is that in reality, low code results in lower cost. Low code development leads to faster app development which saves a lot of time and as a result, lower cost.

It's not only good for companies but also for developers. It certainly cut out the intermediaries, and while they charge less, they use fewer resources and finally come out on top. It is fun for developers because it stops them from actually finding themselves stuck on one particular project which seems to last forever. This is why most of the companies hire app developer who is a well-versed with low-code development.

3. Better Accessibility

The lesser amount of code an application uses, the lesser bandwidth is needed to download it as well as run it. This is quite good news for the people who are based in rural areas or in different developing countries where access to the internet isn’t as prevalent as Western countries. Also, as low code applications can easily be created quite easily than a traditional app, they can easily be released much more swiftly and at a much lower price, and sometimes for free. iPhone app development services follow this approach because it will help in increasing the uptake of their apps as it reduces the entry barrier for every person from lower-income families.

Innovative Development Approach

Among the most promising instances of a low-code or no-code platform is Uber. The apps tap into Google for Maps, Dropbox for storage, Braintree for payments and much more. The most interesting thing about this is that app programming interfaces of APIs which Uber actually relies upon are easily available to anyone who wishes to use them. Uber took those APIs and then used them to create, which was new without requiring to develop each of those particular individual elements, all by themselves. They developed their own brand on top of it by means of looking at how they could actually differentiate themselves from the rest of the others. Mobile app development services should follow this example to create their own low code mobile app which disrupts the market.

The best thing about this is that it inspires innovation. At present, the marketplace actually decides, and only the best applications rise to the top. Also, low code development easily allows developers to iterate much more quickly and can aim for higher more.

The Role of Artificial Intelligence (AI)

Artificial Intelligence is certainly making big waves in different businesses, and as this technology improves further, it will find its way in different other uncharted areas. Among those areas is the low code app development, where it comes in quite useful for a wide range of tasks and actions including the integration of various data sources or just making sense of an entire unstructured or semi-structured data.

Artificial Intelligence is quite great at analysing and conducting trial and error. Hence, it won’t be quite long until the usage of AI becomes quite a standard part of the low code app development. A mobile application development company can find ways to reduce the total amount of code that it is using through AI and flagging potential and possible improvements.

Conclusion

It is quite certain that low-code or no-code app development is the future of app development for one of the simplest reasons that it is quite easier as well as faster and efficiently uses time. It actually doesn’t matter whether Android app development services or iPhone app development services are on-board with this particular change or not. This is quite inevitable as this approach is the path of least resistance. Also, as the inherent demand for low code platforms keeps in growing, developers will certainly find themselves to adopt it.

It is quite a great news as it will push the developers of mobile application development services to become the best. Also, there won’t be any time to redoing it to create the same thing, or any room for sloppy code as well as lengthy development processes which makes the mobile apps redundant even before they are actually finished. Hence, low-code or no-code development will certainly lead the future of mobile app development, and mobile app developers certainly have to get on the bandwagon, one way or the other.

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company