What is Spring AOP – Let’s explore

Spring AOP

Spring Series,,en,Больш падрабязна Spring AOP у прыкладзе,,en,АОП Асновы,,en,У сучаснай складанай распрацоўцы прыкладанняў наступныя пункты заўсёды захоўваюцца ў якасці зоны факусоўкі,,en,Перавага такога падыходу складаецца ў тым,,en,Прастата абслугоўвання і павышэнне прыкладання,,en,Кампаненты могуць быць паўторна выкарыстаны ў існуючых ці новых прыкладаннях,,en,Зніжае затраты на тэхнічнае абслугоўванне і павышэнне,,en,Зараз для вырашэння гэтых праблем вясной распрацавалі такія паняцці, як МАК і АОП,,en,Мы ўжо абмяркоўвалі МАК, так што зараз мы засяродзімся на АОП,,en,АОП арыентавана на функцыянальныя магчымасці прыкладання,,en,як лесанарыхтоўкі,,en,здзелка і г.д.,,en,якія выкарыстоўваюцца на працягу прымянення ў розных галінах,,en,Выкарыстанне АОП гэтыя,,en,скразная,,en,Функцыянальныя магчымасці распрацаваны ў якасці шматкроць выкарыстоўванага кампанента і ўводзяць у дадатак, у якім калі-небудзь патрабаванай,,en – Learn Spring AOP by Example

AOP Basics

In today’s complex application development the following points are always kept as a focus area.

  • Application should be developed as a combination of modular components.
  • All the components should be loosely coupled.
  • Components should be reusable.

The advantage of this approach is

  • Easy maintenance and enhancement of the application.
  • Components can be reused in the existing or new application.
  • Reduces the cost of maintenance and enhancement.

Now to address these concerns spring has developed the concepts like IOC and AOP. We have already discussed IOC so now we will concentrate on AOP.

Spring AOP

AOP targets the application functionalities (like logging, transaction etc) which are used throughout the application in different areas. Using AOP these cross-cutting functionalities are developed as a reusable component and injected into the application where ever required. І зноў уся канфігурацыя ажыццяўляецца з дапамогай файлаў XML,,en,рэалізацыя АОП,,en,Наступная дыяграма паказвае сістэму кіравання падарожжа,,en,Заказ білетаў »,,en,Забраніраваць Hotel »,,en,планаванне паездкі,,en,»Розныя функцыянальныя,,en,Зараз усе гэтыя функцыянальныя магчымасці патрабуюць паслуг, такіх як лесанарыхтоўкі,,en,здзелка і бяспека,,en,Такім чынам, гэта крыж тычыцца рэзкі, якія прыходзяць ва ўсіх модулях,,en,Гэтыя праблемы распрацаваны на аснове прынцыпу АОП,,en,Усе агульныя праблемы распрацоўваюцца ў якасці ўбудовы,,en,таму ён можа быць выкарыстаны ў будучых модулях, а таксама,,en,Вам проста трэба наладзіць яго так, што паслуга таксама даступная ў новых модулях,,en,Гэта сіла аспект арыентаванага праграмавання,,en,АОП,,en,АОП таксама ўжываецца ў прыкладаннях ўзроўню прадпрыемства,,en,У карпаратыўным дадатку,,en,каротажа,,en.

Implementation of AOP

Following diagram shows a travel management system. ‘Ticket Booking’, ‘Hotel Booking’ and ‘Travel Planning’ are different functionalities. Now all of these functionalities require services like logging, transaction and security. So these are cross cutting concerns which come across all the modules. These concerns are developed based on the principle of AOP.

All the common concerns are developed as a plug-in, so it can be used in future modules as well. You just need to configure it so that the service is also available in your new modules. This is the power of aspect oriented programming (AOP).

AOP is also applied in enterprise level applications. In enterprise application, здзелка, logging, бяспека і многія іншыя функцыі ёсць як крыж праблем рэзання,,en,Такім чынам, усе яны распрацаваны як аспекты і сканфігураваны ў XML-файле,,en,Самым вялікім перавагай з'яўляецца слабая сувязь,,en,Паколькі ўсе асцярогі самакіравальнай і незалежныя,,en,так што вы можаце змяніць і палепшыць іх згодна з вашым патрабаванні без закранання кода прыкладання,,en,Сістэма кіравання Падарожжы,,en,Цяпер мы апішам рэалізацыю АОП, паказваючы прыклад,,en,Спачатку мы вызначым інтэрфейс і яго клас рэалізацыі,,en,Гэта простае прыкладанне для параўнання двух цэлалікавых значэнняў і вяртае вынік,,en,Java з'яўляецца вызначэнне інтэрфейсу для параўнання двух цэлалікавых значэнняў,,en,пакет com.techalpine,,en,адкрыты інтэрфейс CompareInt,,en,грамадскага Струнны параўнаць,,en,Java з'яўляецца класам рэалізацыі,,en,Ён параўноўвае два цэлалікавых значэння і вяртае вынік,,en. So all of these are developed as aspects and configured in xml file.

The biggest advantage is loose coupling. As all the concerns are self-managed and independent, so you can change and enhance them as per your requirement without touching the application code.







Travel Management System

Now we will describe the AOP implementation by showing an example.

To start with, first we will define an interface and its implementation class. This is a simple application to compare two integer values and return the result.

Java is the interface definition to compare two integer values

package com.techalpine;

public interface CompareInt{

public String compare(int a,int b);

}

Java is the implementation class. It compares two integer values and returns the result

package com.techalpine;

грамадскі клас CompareIntImpl рэалізуе CompareInt,,en,вяртаць »больш» б,,en,б больш, чым,,en,Цяпер мы напішам просты савет называцца перад выклікам параўнання,,en,Рэкамендацыі будуць падрабязна абмеркаваны ў наступных раздзелах,,en,Цяпер вы можаце сабе ўявіць рэкамендацыі ў якасці задачы, якая будзе ўстаўлена ў дадатак праз канфігурацыю XML,,en,І гэта будзе выклікацца перад выклікам метаду,,en,Але там не будзе мець ніякага прамога кадавання ўнутры класа рэалізацыі,,en,Мы будзем прымаць толькі перад саветам для рэалізацыі класа,,en,імпарт java.lang.reflect.Method,,en,імпарт org.springframework.aop.MethodBeforeAdvice,,en,грамадскі клас LogBefore рэалізуе MethodBeforeAdvice,,en,грамадскага несапраўднымі да таго,,en,мэтавай аб'ект,,en,Перад выклікам метаду параўнання,,en,Цяпер мы абмяркуем аб файле канфігурацыі,,en,Тэст-aop.xml,,en{

public String compare(int a, int b){

калі (a>сі)

{

return a ” is greater than” b;

}

яшчэ

{

return “b is greater than a”;

}

}

}

Now we will write a simple advice to be called before calling the compare (дзесятковага, дзесятковага) метад. The advice will be discussed in details in the following chapters. Now you can imagine advice as a task which will be plugged into the application through xml configuration. And this will be called before the method is called. But there will not have any direct coding inside the implementation class. We will only take before advice for the implementation class.







package com.techalpine;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

public class LogBefore implements MethodBeforeAdvice{

public void before(Method method, аб'ект[] аргументы, Object target) {

System.out.println(“Before Calling the compare Method”);

}

}

Now we will discuss about the configuration file (Test-AOP.xml)

Файл складаецца з трох раздзелаў,,en,Першы раздзел з'яўляецца вызначэннем саветаў боба,,en,Другі раздзел вызначае клас рэалізацыі,,en,Трэці раздзел вызначае звязванне кансультацый з класам рэалізацыі,,en,www.springframework.org/schema/beans/spring-beans-2.0.xsd,,en,парады,,en,рожкового ID =,,en,beforeCall,,en,клас =,,en,com.techalpine.LogBefore,,pt,клас рэалізацыі,,en,compareImpl,,en,com.techalpine.CompareIntImpl,,pt,Proxy Класс рэалізацыі,,en,параўнаць,,en,org.springframework.aop.framework.ProxyFactoryBean,,en,імя ўласцівасці =,,en,proxyInterfaces,,en,com.techalpine.CompareInt,,pt,interceptorNames,,en,исй = боб,,en,Цяпер апошняя частка тэсту класа CompareTest.java,,en,Ён загружае вызначэнне Біна з дапамогай XmlBeanFactory класа, а затым называецца параўнаць,,en,імпарт org.springframework.beans.factory.BeanFactory,,en,імпарт org.springframework.beans.factory.xml.XmlBeanFactory,,en,імпартаваць org.springframework.core.io. *,,it,грамадскі клас CompareTest,,en

  • The first section is the advice bean definition
  • The second section defines the implementation class
  • The third section defines the binding of the advice with the implementation class

<beans xmlns=”HTTP://www.springframework.org/schema/beans”

xmlns:xsi=”HTTP://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation=”HTTP://www.springframework.org/schema/beans

HTTP://www.springframework.org/schema/beans/spring-beans-2.0.xsd”>

<!– Advices –>

<bean id = “beforeCall”

class = “com.techalpine.LogBefore” />

<!– Implementation Class –>

<bean id = “compareImpl”

class = “com.techalpine.CompareIntImpl ” />

<!– Proxy Implementation Class –>

<bean id = “compare”

class = “org.springframework.aop.framework.ProxyFactoryBean”>

<property name = “proxyInterfaces”>

<значэнне>com.techalpine.CompareInt</значэнне>

</ўласнасць>

<property name = “interceptorNames”>

<list>

<значэнне>beforeCall</значэнне>

</list>

</ўласнасць>

<property name = “target”>

<ref bean = “compareImpl”/>

</ўласнасць>

</bean>

</beans>

Now the last part is the test class CompareTest.java. It loads the bean definition by using XMLBeanFactory class and then called the compare () метад.

package com.techalpine;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.*;

public class CompareTest {

дзяржаўнай статычнай сілы асноўных(String args[]){

Рэсурс рэсурс = новы FileSystemResource,,en,SRC / Тэст-aop.xml,,en,BeanFactory завод = новы XmlBeanFactory,,en,рэсурс,,en,З CompareInt =,,pt,суматар,,en,factory.getBean,,en,Вынік String = com.compare,,en,Вынік =,,en,вынік,,en,Выхад з параўнання,,en,выклік метаду будзе выглядаць наступным чынам,,en,Перад выклікам метаду параўнання,,en,больш,,en,Spring AOP вельмі карысна, калі мы спрабуем аддзяліць бізнес-логіку ад крыжаваных праблем рэжучых,,en,Ён шырока выкарыстоўваецца ў розных формах, каб ахапіць розныя аспекты,,en,АОП таксама можа быць рэалізаваны і ў іншых мовах праграмавання,,en(“./src/Test-AOP.xml”);

BeanFactory factory = new XmlBeanFactory(resource);

CompareInt com = (Adder)factory.getBean(“compare”);

String result = com.compare(12,10);

System.out.println(“Result = ” + result);

}

}

The output of the compare () method call would be as follows

Before calling the compare Method

12 is greater than 10







Заключэнне:

Spring AOP is very helpful when we try to separate business logic from cross cutting concerns. It is widely used in different forms to cover various aspects. AOP can also be implemented in other programming languages.

 

Tagged on: ,
============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share