Nearby lessons

15 of 35

Spring - AOP (Aspect Oriented Programming)

📌 What You Will Learn
  • Understand Spring - AOP (Aspect Oriented Programming)
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Spring - AOP (Aspect Oriented Programming) step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

Aspect Orientation

In general, in enterprise applications development, if we use Object Oriented Programming languages then we have to provide the implementation by combining both Applications business logic and services logic.

Example01
JCode Cell
1 
2public class Transaction{
3public void deposit(---){
4----Deposit Logic-----
5----Authentocation-----
6----Logging------------
7----Transact-----------
8}
9public void withdraw(---){
10----Deposit Logic-----
11----Authentication-----
12----Logging------------
13----Transact-----------
14}
15public void transfer(---){
16----Deposit Logic-----
17----Authentication-----
18----Logging------------
19----Transact-----------
20}
21}
22

Aspect Orientation

If we use the above style of implementation then we are able to get the following problems.

  • It is very difficult to modify the services logic, it required to modify in all business method.
  • It will not provide Sharability
  • It will not provide Code Reusability.
  • It will provide tightly coupled design.

To overcome the above problems we have to use Aspect Orientation. Aspect Orientation is not a programming language, it is a methodology or a paradiagm, it will be applied on Object Oriented Programming in order to get loosely coupled design and in order to improve sharability and Reusability. The basic idea behind Aspect Orientation is to separate all services logic from System Business logic , declaring each and every service as an aspect and injecting these aspects into the application Business logic in the respective locations by using Dependence Injection.

In enterprise Applications, AOP will provide the following advantages.

  • In Enterprise applications, Business components looks very clean and having only business implementation statements.
  • All Services are implemented in a common place which simplifies code maintenance.
  • We can make changes in common location , so that, the changes are reflected to all business methods.

AOP is implemented by the following vendors.

  • AspectJ
  • Spring AOP
  • JBOSS AOP

Spring Framework is providing the following two types of implementations

  • Schema Based Implementation
  • AspectJ
  • Declarative Based Approach
  • Annotation Based Approach

AOP Terminology

In general, AOP will use the following terminologies inorder to implement AOP based implementation.

  • Aspect
  • Advice
  • Join point
  • Pointcut
  • Target
  • Proxy
  • Weaving
  • Introduction

Aspect

An Aspect is the concern or a service which we want to implement in the application such as logging, transactional , Security etc.

Advice

An Advice is the actual implementation of the aspect. Aspect is a concept and Advice is the concrete implementation of the concept.

Join point

A JoinPoint is a point in the execution of the program where an aspect can be applied. It could be before/after executing the method, before throwing an exception, before/after modifying an instance variable etc.

Pointcut

PointCuts tell on which join points the aspect will be applied. An advice is associated with a point cut expression and is applied to a join point which matches the point cut expression.

Target

Target is a business component class which is being advised

Proxy

Proxy is the object which is created by the framework after applying the advice on the target object. Proxy = target + advice(s)

Weaving

Weaving is the process of applying the aspect on the target object to product the proxy object. Weaving can be done at compile time, class loading time or runtime. Spring AOP supports weaving at runtime.

Introduction

An Introduction allows adding new methods or attributes to existing classes. The new method and instance variable can be introduced to existing classes without having to change them, giving them new state and behavior. Advices In Spring

Advices In Spring

Advice is the implementation of Aspect. An Advice provides the code for implementation of the service or Aspect. As an example consider logging service, logging is an Aspect and Advice denotes the implementation of Log4j.

In general, all the advices code will not be included in business methods at compile time, these services will be included at runtime.

Spring Framework is providing the following various advices.

  • Before Advice
  • After Advice
  • After-Returning
  • After-throwing
  • Around Advice

Before Advice

Before advice contains service/Aspect implementation , it will be executed before executing the respective business method.

To represent Before Advice, Spring Framework has provided a predefined interface in the form of "org.springframework.aop.MethodBeforeAdvice".

If we want to use Before Advice in Spring applications , first, we have to declare an user defined class, it must implement org.springframework.aop.MethodBeforeAdvice interface and we must provide implementation for the following method provided by MethodBeforeAdvice interface.

public void before(Method m,Object[] Bus_Meth_Params, Object target)throws Exception

 Where java.lang.reflect.Method parameter is able to provide metadata of the Business method to which BeforeAdvice is applied.

 Where Object[] is providing business method parameter values in the form of Objects.  Where Object is representiung the target Object.

Note: The services which are implemented in before() method are executed at before executing business logic.

Example13
JCode Cell
1 
2public class BeforeAdviceImpl implements MethodBeforeAdvice{
3public void before(Method method, Object[] params, Object target)throws Exception{
4-----Service implementation-----
5}
6}
7

After Advice[After Returning Advice]

It is same as Before Advice, But this advice contains services which are applied after completion of our business method logic To create an after returning advice in spring, we have to declare an user defined class, it must implement org.springframework.aop.AfterReturningAdvice and we must implement the following method.

public void afterReturning(Object returnValue,Object[] args, Object target)throws Exception

 Where first parameter is representning return value in the form of Object type.  Where second parameter is able to represent business method parameters in the form of

Object[].  Where third parameter is representing Target Object.

Example14
JCode Cell
1 
2public class AfterReturningAdviceImpl implements AfterReturningAdvice{
3public void afterReturning(Object returnValue,Object[] args, Object target)throws Exception{
4----
5}
6}
7

After Advice[After Returning Advice]

Note: In Schema Based implementation, After Advice and After-Returning Advice are same, but, in Annotation approach both are different.

After-throwing or Throws Advice

This advice will be executed after throwing an exception from the business method.

To represent After-Throwing Advice, Spring Framework has provided a predefined interface in the form of "org.springframework.aop.ThrowsAdvice".

If we want to use After Throwing Advice in Spring applications , first, we have to declare an user defined class, it must implement org.springframework.aop.ThrowsAdvice interface and we must provide implementation for the following method provided by ThrowsAdvice interface. public void afterThrowing([Method, args, target], ThrowableSubclass)

Some Examples of the above form are public void afterThrowing(Exception ex) public void afterThrowing(RemoteException) public void afterThrowing(Method method, Object[] args, Object target, Exception ex) public void afterThrowing(Method method, Object[] args, Object target, ServletException ex)

 Where java.lang.reflect.Method parameter is able to provide metadata of the Business method to which BeforeAdvice is applied.

 Where Object[] is providing business method parameter values in the form of Objects.  Where Object is representiung the target Object.  Where Exception is representing the generated Exception.

Example16
JCode Cell
1 
2public class ThrowsAdviceImpl implements ThrowsAdvice{
3public void afterThrows(Method method, Object[] params, Object target)throws Exception {
4-----Service implementation-----
5}
6}
7

Around Advice

Around Advice will be executed before and after executing the business method. Around Advice is combination of both Before and After Advice. Around Advice is not given by spring framework and it is from Open Source implementation called AOP alliance. Around Advice can be used by any framework which supports AOP.

To represent Around Advice, Spring AOP Aliance has provided a predefined interface in the form of org.aopalliance.intercept.MethodInterceptor.

MethodINterceptor has provided the following method inorder to provide services before and after execution of the business method.

public Object invoke(MethodInvocation mi)throws Throwable

In Around Advice, we will implement Before and After Advice in invoke() method, in invoke() method will provide before advice logic before calling proceed() method and we will provide After Advice logic after calling proceed() method.

Note: Around Advice can access the return value of business method and it can modify the value and it can return a different value back to the client, as return type is Object, but in the After Advice its not possible right, as its return type is void.

Example17
JCode Cell
1 
2public class AroundAdviceImpl implements MethodInterceptor
3{
4public Object invoke(MethodInvocation mi)throws Throwable
5{
6 //Before Logic
7 Object ob = mi.proceed();
8 //After logic
9 return ob;
10}
11}
12

PointCut

PointCut defines at what Joinpoints Advices has to be applied, instead of defining advices at all join points.

If we want to use PointCuts in AOP based applications then we have to configure that pointcuts in Spring configuration File.

To configure Pointcuts in configuration file then we have to use the following two types of PointCuts.

  • Static Pointcut
  • Dynamic Pointcut

Static Pointcut

Static pointcuts define advice that is always executed. Static pointcuts are based on method and target class, and cannot take into account the method's arguments. Static pointcuts are sufficient - and best - for most usages. It's possible for Spring to evaluate a static pointcut only once, when a method is first invoked: after that, there is no need to evaluate the pointcut again with each method invocation.

To represent Pointcuts , Spring framework has provided a predefined interface in the form of "org.springframework.aop.PointCut". SpringFramework has provided the following Implementation classes for org.springframework.aop.PointCut interface.

  • NameMatchMethodPointcut
  • Perl5RegexpMethodPointcut
  • JdkRegexpMethodPointcut

Dynamic Pointcut

Dynamic pointcuts determine if advice should be executed by examining the runtime method arguments.

Dynamic pointcuts are costlier to evaluate than static pointcuts. They take into account method arguments, as well as static information. This means that they must be evaluated with every method invocation; the result cannot be cached, as arguments will vary.

To represent Dynamic Pointcut Spring has provided the following predefined class.

  • ControlFlowPointcut
  • DynamicMethodMatcherPointcut

If we want to use Pointcuts in Spring applications then we have to configure Pointcut and Advisor in apring configuration file.

In spring applications, we will use "DefaultPointCutAdvosor" inorder to suggest the advices to the Pointcuts.

Where if we want to use NameMatchMethodPointcut then we have to use "mappedNames" property of type "array" and we must provide business method names as values to which we want to apply advices.

Example20
JCode Cell
1 
2<bean id="pointcut" class="org.springframework.aop.support.NameMatchMethodPointcut">
3<property name="mappedNames">
4 <array>
5 <value>displayEmployee</value>
6 <value>getEmployeeDetails</value>
7 </array>
8</property>
9</bean>
10

Dynamic Pointcut

 Where If we want to use "Perl5RegexpMethodPointcut" and "JdkRegexpMethodPointcut" in

spring applications then we have to use a property like "pattern" of list type with different patterns.

Example21
JCode Cell
1 
2<bean id="pointcut" class="org.springframework.aop.support.Perl5RegexpMethodPointcut">
3<property name="patterns">
4 <list>
5 <value>.*Employee.*</value>
6 </list>
7</property>
8</bean>
9

Dynamic Pointcut

 Where if we want to use DefaultPointcutAdvisor in spring applications then we have to use "pointcut" and "advice" properties.

Example22
JCode Cell
1 
2<bean id="advisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
3<property name="pointcut" ref="pointcut"/>
4<property name="advice" ref="validatorAdvice"/>
5</bean>
6

Example On Before Advice — Employee.java

Example23
JCode Cell
1 
2package com.durgasoft.beans;
3 
4public class Employee {
5private int eno;
6private String ename;
7private float esal;
8private String eemail;
9private String emobile;
10 
11public int getEno() {
12return eno;
13}
14public void setEno(int eno) {
15this.eno = eno;
16}
17public String getEname() {
18return ename;
19}
20public void setEname(String ename) {
21this.ename = ename;
22}
23public float getEsal() {
24return esal;
25}
26public void setEsal(float esal) {
27this.esal = esal;
28}
29public String getEemail() {
30return eemail;
31}
32public void setEemail(String eemail) {
33this.eemail = eemail;
34}
35public String getEmobile() {
36return emobile;
37}
38public void setEmobile(String emobile) {
39this.emobile = emobile;
40}
41 
42 
43}
44

Example On Before Advice — EmployeeService.java

Example24
JCode Cell
1 
2package com.durgasoft.bo;
3 
4import com.durgasoft.beans.Employee;
5 
6public interface EmployeeService {
7public void displayEmployee(Employee emp);
8public void getEmployeeDetails(Employee emp);
9}
10

Example On Before Advice — EmployeeServiceImpl.java

Example25
JCode Cell
1 
2package com.durgasoft.bo;
3 
4import com.durgasoft.beans.Employee;
5 
6public class EmployeeServiceImpl implements EmployeeService {
7 
8@Override
9public void displayEmployee(Employee emp) {
10 System.out.println("Employee Details from displayEmployee(---)");
11System.out.println("----------------------------------------------");
12System.out.println("Employee Number :"+emp.getEno());
13System.out.println("Employee Name :"+emp.getEname());
14System.out.println("Employee Salary :"+emp.getEsal());
15System.out.println("Employee Email Id :"+emp.getEemail());
16System.out.println("Employee Mobile No :"+emp.getEmobile());
17 
18}
19public void getEmployeeDetails(Employee emp) {
20System.out.println("Employee Details from getEmployeeDetails(--)");
21System.out.println("---------------------------------------------------");
22System.out.println("Employee Number :"+emp.getEno());
23System.out.println("Employee Name :"+emp.getEname());
24System.out.println("Employee Salary :"+emp.getEsal());
25System.out.println("Employee Email Id :"+emp.getEemail());
26System.out.println("Employee Mobile No :"+emp.getEmobile());
27 
28}
29 
30}
31

Example On Before Advice — EmployeeValidator.java

Example26
JCode Cell
1 
2package com.durgasoft.advice;
3 
4import java.lang.reflect.Method;
5 
6import org.springframework.aop.MethodBeforeAdvice;
7 
8 
9import com.durgasoft.beans.Employee;
10 
11public class EmployeeValidator implements MethodBeforeAdvice {
12 
13@Override
14public void before(Method method, Object[] params, Object target) throws Throwable {
15Employee emp = (Employee) params[0];
16System.out.println("Validation Messages for "+method.getName());
17System.out.println("-----------------------------------------------");
18if( emp.getEno() < 100 || emp.getEno() > 999) {
19 System.out.println("*********Employee Number must be 3 digit number **********");
20}
21if( emp.getEsal() < 20000 || emp.getEsal() > 50000) {
22 System.out.println("********* Employee Salary Must be in between 20000 to 50000 ********");
23}
24if(!emp.getEemail().endsWith("@durgasoft.com")) {
25 System.out.println("********* Employee Email is Invalid *************");
26}
27if(!emp.getEmobile().startsWith("91-")) {
28 System.out.println("********* Employee Mobile Number is INvalid ********");
29}
30}
31}
32

Example On Before Advice — ApplicationContext.java

Example27
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:aop="http://www.springframework.org/schema/aop"
6xsi:schemaLocation="
7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
8 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
9<!-- Bean Object -->
10<bean id="empBean" class="com.durgasoft.beans.Employee">
11<property name="eno" value="12345"/>
12<property name="ename" value="AAA"/>
13<property name="esal" value="10000"/>
14<property name="eemail" value="aaa@gmail.com"/>
15<property name="emobile" value="9988776655"/>
16</bean>
17 
18<!-- Target Object -->
19<bean id="empService" class="com.durgasoft.bo.EmployeeServiceImpl"/>
20 
21<!-- Advice -->
22<bean id="validatorAdvice" class="com.durgasoft.advice.EmployeeValidator"/>
23 
24<!-- Pointcut -->
25<bean id="pointcut" class="org.springframework.aop.support.NameMatchMethodPointcut">
26<property name="mappedNames">
27 <array>
28 <value>displayEmployee</value>
29 <value>getEmployeeDetails</value>
30 </array>
31</property>
32</bean>
33 
34<!-- Advisor -->
35<bean id="advisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
36<property name="pointcut" ref="pointcut"/>
37<property name="advice" ref="validatorAdvice"/>
38 
39</bean>
40 
41<!-- Proxy Object -->
42<bean id="empProxy" class = "org.springframework.aop.framework.ProxyFactoryBean">
43<property name="target" ref="empService"/>
44<property name="interceptorNames">
45 <list>
46 <value>advisor</value>
47 </list>
48</property>
49</bean>
50</beans>
51

Example On Before Advice — Test.java

Example28
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.springframework.aop.support.DefaultPointcutAdvisor;
5import org.springframework.aop.support.NameMatchMethodPointcut;
6import org.springframework.context.ApplicationContext;
7import org.springframework.context.support.ClassPathXmlApplicationContext;
8 
9import com.durgasoft.beans.Employee;
10import com.durgasoft.bo.EmployeeService;
11 
12public class Test {
13 
14public static void main(String[] args) {
15ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
16Employee emp = (Employee) context.getBean("empBean");
17EmployeeService empService = (EmployeeService) context.getBean("empProxy");
18empService.displayEmployee(emp);
19System.out.println();
20empService.getEmployeeDetails(emp);
21 
22 
23}
24}
25

Example On After Advice — Student.java

Example29
JCode Cell
1 
2package com.durgasoft.beans;
3 
4public class Student {
5private String sname;
6private String squal;
7private String semail;
8private String smobile;
9 
10public String getSname() {
11return sname;
12}
13public void setSname(String sname) {
14this.sname = sname;
15}
16public String getSqual() {
17return squal;
18}
19public void setSqual(String squal) {
20this.squal = squal;
21}
22public String getSemail() {
23return semail;
24}
25public void setSemail(String semail) {
26this.semail = semail;
27}
28public String getSmobile() {
29return smobile;
30}
31public void setSmobile(String smobile) {
32this.smobile = smobile;
33}
34 
35 
36}
37

Example On After Advice — InstituteService.java

Example30
JCode Cell
1 
2package com.durgasoft.bo;
3 
4import com.durgasoft.beans.Student;
5 
6public interface InstituteService {
7public void enquiry(Student std, String course_Name);
8public void registration(Student std, String course_name);
9}
10

Example On After Advice — InstituteServiceImpl.java

Example31
JCode Cell
1 
2package com.durgasoft.bo;
3 
4import com.durgasoft.beans.Student;
5 
6public class InstituteServiceImpl implements InstituteService {
7 
8@Override
9public void enquiry(Student std, String course_Name) {
10 System.out.println("Student Enquiry Details");
11System.out.println("-----------------------------");
12System.out.println("Student Name :"+std.getSname());
13System.out.println("Student Qualification :"+std.getSqual());
14System.out.println("Student Email ID :"+std.getSemail());
15System.out.println("Student Mobile NUmber :"+std.getSmobile());
16System.out.println("Enquiry Course Name :"+course_Name);
17}
18public void registration(Student std, String course_Name) {
19System.out.println("Student Course Registration Details");
20System.out.println("-------------------------------------");
21System.out.println("Student Name :"+std.getSname());
22System.out.println("Student Qualification :"+std.getSqual());
23System.out.println("Student Email ID :"+std.getSemail());
24System.out.println("Student Mobile NUmber :"+std.getSmobile());
25System.out.println("Enquiry Course Name :"+course_Name);
26}
27}
28

Example On After Advice — ThanqAdvice.java

Example32
JCode Cell
1 
2package com.durgasoft.advice;
3 
4import java.lang.reflect.Method;
5 
6import org.springframework.aop.AfterReturningAdvice;
7 
8import com.durgasoft.beans.Student;
9 
10public class ThanqAdvice implements AfterReturningAdvice {
11 
12@Override
13public void afterReturning(Object return_Val, Method method, Object[] params, Object target) throws Throwable {
14Student std = (Student)params[0];
15String course_Name = (String)params[1];
16System.out.println("ThanQ "+std.getSname()+" for your course "+method.getName()+" on "+course_Name);
17System.out.println("Durgasoft Team will contact with you for the Course Schedule");
18}
19}
20

Example On After Advice — ApplicationContext.java

Example33
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:aop="http://www.springframework.org/schema/aop"
6xsi:schemaLocation="
7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
8 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
9 
10<!-- Beans -->
11<bean id="stdBean" class="com.durgasoft.beans.Student">
12<property name="sname" value="Durga"/>
13<property name="squal" value="BTech"/>
14<property name="semail" value="durga@gmail.com"/>
15<property name="smobile" value="91-9988776655"/>
16</bean>
17 
18<!-- Target -->
19<bean id="target" class="com.durgasoft.bo.InstituteServiceImpl"/>
20 
21<!-- Advice -->
22<bean id="advice" class="com.durgasoft.advice.ThanqAdvice"/>
23 
24<!-- Proxy -->
25<bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
26<property name="target" ref="target"/>
27<property name="interceptorNames">
28 <list>
29 <value>advice</value>
30 </list>
31</property>
32</bean>
33</beans>
34

Example On After Advice — Test.java

Example34
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.springframework.context.ApplicationContext;
5import org.springframework.context.support.ClassPathXmlApplicationContext;
6 
7import com.durgasoft.beans.Student;
8import com.durgasoft.bo.InstituteService;
9 
10public class Test {
11public static void main(String[] args) {
12ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
13Student std = (Student) context.getBean("stdBean");
14InstituteService inst_Service = (InstituteService) context.getBean("proxy");
15inst_Service.enquiry(std, "JAVA");
16System.out.println();
17inst_Service.registration(std, "JAVA");
18 
19 
20}
21}
22

Example On Throws Advice — Movie.java

Example35
JCode Cell
1 
2package com.durgasoft.beans;
3 
4public class Movie {
5private String movie_Name;
6private String show_Time;
7private int price;
8 
9public String getMovie_Name() {
10 return movie_Name;
11}
12public void setMovie_Name(String movie_Name) {
13this.movie_Name = movie_Name;
14}
15public String getShow_Time() {
16return show_Time;
17}
18public void setShow_Time(String show_Time) {
19this.show_Time = show_Time;
20}
21public int getPrice() {
22return price;
23}
24public void setPrice(int price) {
25this.price = price;
26}
27 
28 
29}
30

Example On Throws Advice — MovieService.java

Example36
JCode Cell
1 
2package com.durgasoft.bo;
3 
4import com.durgasoft.beans.Movie;
5 
6public interface MovieService {
7public void playMovie(Movie movie)throws Exception;
8}
9

Example On Throws Advice — MovieServiceImpl.java

Example37
JCode Cell
1 
2package com.durgasoft.bo;
3 
4import com.durgasoft.beans.Movie;
5 
6public class MovieServiceImpl implements MovieService {
7 
8@Override
9public void playMovie(Movie movie)throws Exception {
10 System.out.println("Movie Details");
11System.out.println("----------------");
12System.out.println("Movie Name :"+movie.getMovie_Name());
13System.out.println("Movie Time :"+movie.getShow_Time());
14System.out.println("Price :"+movie.getPrice());
15throw new RuntimeException("Power Failure Occurred");
16}
17 
18}
19

Example On Throws Advice — MoneyReturnAdvice.java

Example38
JCode Cell
1 
2package com.durgasoft.advice;
3 
4 
5import java.lang.reflect.Method;
6 
7import org.springframework.aop.ThrowsAdvice;
8 
9 
10public class MoneyReturnAdvice implements ThrowsAdvice {
11public void afterThrowing(Method method, Object[] params, Object target, Exception e) {
12System.out.println("Power Failure Exception Occurred, Movie was stopped, please come to counter and collect your money");
13 
14}
15}
16

Example On Throws Advice — ApplicationContext.java

Example39
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:aop="http://www.springframework.org/schema/aop"
6xsi:schemaLocation="
7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
8 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
9<!-- Beans -->
10<bean id = "movieBean" class="com.durgasoft.beans.Movie">
11<property name="movie_Name" value="Bahubali"/>
12<property name="show_Time" value="6:00pm"/>
13<property name="price" value="250"/>
14</bean>
15 
16<!-- Target -->
17<bean id="target" class="com.durgasoft.bo.MovieServiceImpl"/>
18 
19<!-- Advice -->
20<bean id="advice" class="com.durgasoft.advice.MoneyReturnAdvice"/>
21 
22<!-- Proxy -->
23<bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
24<property name="target" ref="target"/>
25<property name="interceptorNames">
26 <list>
27 <value>advice</value>
28 </list>
29</property>
30</bean>
31</beans>
32

Example On Throws Advice — Test.java

Example40
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.springframework.context.ApplicationContext;
5import org.springframework.context.support.ClassPathXmlApplicationContext;
6 
7import com.durgasoft.beans.Movie;
8import com.durgasoft.bo.MovieService;
9 
10public class Test {
11 
12public static void main(String[] args) {
13ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
14Movie movie = (Movie)context.getBean("movieBean");
15 
16MovieService movie_Service = (MovieService) context.getBean("proxy");
17try {
18 movie_Service.playMovie(movie);
19} catch (Exception e) {
20 
21}
22 
23}
24 
25}
26

Example on Around Advice — Account.java

Example41
JCode Cell
1 
2package com.durgasoft.beans;
3 
4public class Account {
5private String accNo;
6private String accName;
7private String accType;
8private int balance;
9 
10public String getAccNo() {
11return accNo;
12}
13public void setAccNo(String accNo) {
14this.accNo = accNo;
15}
16public String getAccName() {
17return accName;
18}
19public void setAccName(String accName) {
20this.accName = accName;
21}
22public String getAccType() {
23return accType;
24}
25public void setAccType(String accType) {
26this.accType = accType;
27}
28public int getBalance() {
29return balance;
30}
31public void setBalance(int balance) {
32this.balance = balance;
33}
34 
35 
36}
37

Example on Around Advice — Cheque.java

Example42
JCode Cell
1 
2package com.durgasoft.beans;
3 
4public class Cheque {
5private String cheque_No;
6private int amount;
7 
8public String getCheque_No() {
9 return cheque_No;
10}
11public void setCheque_No(String cheque_No) {
12this.cheque_No = cheque_No;
13}
14public int getAmount() {
15return amount;
16}
17public void setAmount(int amount) {
18this.amount = amount;
19}
20}
21

Example on Around Advice — TransactionService.java

Example43
JCode Cell
1 
2package com.durgasoft.bo;
3 
4import com.durgasoft.beans.Account;
5import com.durgasoft.beans.Cheque;
6 
7public interface TransactionService {
8public void debit(Account acc, Cheque cheque );
9}
10

Example on Around Advice — TransactionServiceImpl.java

Example44
JCode Cell
1 
2package com.durgasoft.bo;
3 
4import com.durgasoft.beans.Account;
5import com.durgasoft.beans.Cheque;
6 
7public class TransactionServiceImpl implements TransactionService {
8 
9@Override
10public void debit(Account acc, Cheque cheque) {
11int initial_Amount = acc.getBalance();
12int debit_Amount = cheque.getAmount();
13int total_Amount = initial_Amount - debit_Amount;
14acc.setBalance(total_Amount);
15System.out.println("*******Transaction Success*******************");
16System.out.println("*******Amount is debited from Account********");
17}
18}
19

Example on Around Advice — ChequeClearenceAdvice.java

Example45
JCode Cell
1 
2package com.durgasoft.advice;
3 
4import org.aopalliance.intercept.MethodInterceptor;
5import org.aopalliance.intercept.MethodInvocation;
6 
7 
8import com.durgasoft.beans.Account;
9import com.durgasoft.beans.Cheque;
10 
11public class ChequeClearenceAdvice implements MethodInterceptor {
12 
13@Override
14public Object invoke(MethodInvocation mi) throws Throwable {
15 
16Object[] params = mi.getArguments();
17Account acc = (Account)params[0];
18Cheque cheque = (Cheque)params[1];
19 
20System.out.println("Hello Customer!, Check No "+cheque.getCheque_No()+" is coming for clearence");
21mi.proceed();
22System.out.println("Hello Customer!, Account Number "+acc.getAccNo()+" has been debited the amount "+cheque.getAmount()+" in clearence of the cheque No "+cheque.getCheque_No()+" , Now the total Amount in your Account is "+acc.getBalance() );
23return null;
24}
25 
26}
27

Example on Around Advice — applicationContext.java

Example46
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:aop="http://www.springframework.org/schema/aop"
6xsi:schemaLocation="
7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
8 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
9<!-- Beans -->
10<bean id="accBean" class="com.durgasoft.beans.Account">
11<property name="accNo" value="abc123"/>
12<property name="accName" value="Durga"/>
13<property name="accType" value="Savings"/>
14<property name="balance" value="20000"/>
15</bean>
16<bean id="chequeBean" class="com.durgasoft.beans.Cheque">
17<property name="cheque_No" value="xyz123"/>
18<property name="amount" value="10000"/>
19</bean>
20 
21<!-- Target -->
22<bean id="target" class="com.durgasoft.bo.TransactionServiceImpl"/>
23 
24<!-- Advice -->
25<bean id="advice" class="com.durgasoft.advice.ChequeClearenceAdvice"/>
26 
27<!-- Proxy -->
28<bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
29 <property name="target" ref="target"/>
30 <property name="interceptorNames">
31 <list>
32 <value>advice</value>
33 </list>
34 </property>
35</bean>
36</beans>
37

Example on Around Advice — Test.java

Example47
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.springframework.context.ApplicationContext;
5import org.springframework.context.support.ClassPathXmlApplicationContext;
6 
7import com.durgasoft.beans.Account;
8import com.durgasoft.beans.Cheque;
9import com.durgasoft.bo.TransactionService;
10 
11public class Test {
12 
13public static void main(String[] args) {
14ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
15Account account = (Account) context.getBean("accBean");
16Cheque cheque = (Cheque) context.getBean("chequeBean");
17TransactionService tx_Service = (TransactionService) context.getBean("proxy");
18tx_Service.debit(account, cheque);
19}
20 
21}
22

AspectJ

AspectJ is well known in AOP language, it provides specialized syntax to express concerns. It also provides tools to add a concern into the system and enables crosscutting concern and modularization, such as logging, error checking and handling, and so on.

Spring is supporting AspectJ in the following two ways.

  • Declarative approach
  • @AspectJ annotation style approach

Declarative approach — applicationContext.xml

IN declarative approach, we will use Aspectj Namespace tags inorder to declare aspects, advices, Pointcuts,......

In declarative configuration approach, all the aspect declarations are placed under the <aop:config/> tag.

To use AOP namespace tags, we need to import the spring-aop schema.

Example49
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w
4org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
5

Declarative approach

  • <aop:config>
  • <!-- contains aspect configuration and all method related configuration -->
  • </aop:config>
  • </beans>

Note:The aop:config will contain all aspect configurations and all specific method-related configurations, such as around, pointcut, and so on.

Declaring Aspects

To declare aspects by using AspectJ namespace tags we have to use the following tags.

<aop:config> <aop:aspect id="--" ref="--"> -----
</aop:aspect> <aop:config>

 Where "id" attribute will take Aspect id value.  Where "ref" attribute will take identity of the class ehich has declared in the configuration

file by using <bean> tag in out side of <aop:aspect> tag.

Example51
JCode Cell
1 
2<beans ..... >
3<aop:config>
4 <aop:aspect id="loggingAspect" ref="loggingAspectBean">
5 ...
6 </aop:aspect>
7</aop:config>
8 
9<bean id="loggingAspectBean" class="com.durgasoft.aspect.EmployeeCRUDLoggingAspect" />
10</beans>
11

Declaring Pointcuts

A pointcut helps in determining the join points to be executed with different advices. To declare pointcuts we have to use the following tags in configuration file.

<aop:config> <aop:aspect id="----" ref="----"> <aop:pointcut id="----" expression="------"/>
</aop:aspect>
</aop:config>

 Where "id" attribute in <aop:pointcut> tag will take identity to the Pointcut.  Where "expression" attribute in <aop:pointcut> will take AspectJ expression to define

expression for the business methods which are required Advices.  Where "expression" attribute will take "execution" function with an expression.

EX:

<aop:pointcut id="businessService" expression="execution(* com.durgasoft.service.*.*(..))"/> In the above code, expression will repersent all java methods with any type of return type.
Example52
JCode Cell
1 
2<aop:config>
3<aop:aspect id="loggingAspect" ref="loggingAspectBean">
4 
5 <aop:pointcut id="loggingOperation" expression="execution(* com.durgasoft.service.EmployeeService.*(..))" />
6 
7</aop:aspect>
8</aop:config>
9 
10<bean id="loggingAspectBean" class="com.durgasoft.aspect.EmployeeCRUDLoggingAspect" />
11

Examples on Pointcut Expressions

  • execution (* com.durgasoft.service.EmployeeService.*(..))

 The above Expression matches all of the methods declared in the EmployeeService interface  The above expression matches methods with any modifier (public, protected, and private) and any return type.  The two dots in the argument list match any number of arguments.

  • execution(* EmployeeService.*(..))

 The above Expression matches all methods of EmployeeService interface which are existed in the present package with any type of access modifier and with any return type.

  • execution(public * EmployeeService.*(..))

 The above Expression matches all public methods of EmployeService interface with any return type.

  • execution(public Employee EmployeeService.*(..))

 The above Expression matches all public methods of EmployeeService interface with Employee return type.

  • execution(public Employee EmployeeService.*(Employee, ..))

 The above Expression matches all methods of EmployeeService interface with Employee return type and first parameter as Employee.

  • execution(public Employee EmployeeService.*(Employee, Integer))

 The above Expression matches all public methods of EmployeeService with Employee return type and with Employee as First parameter and Integer type parameter as second.

Declaring Advices

Spring AspectJ is supporting thye following five advices .

  • <aop:before> It is applied before calling the actual business logic method.
  • <aop:after> It is applied after calling the actual business logic method.
  • <aop:after-returning> it is applied after calling the actual business logic method. It can be

used to intercept the return value in advice.

  • <aop:around> It is applied before and after calling the actual business logic method.
  • <aop:after-throwing> It is applied if actual business logic method throws exception.

All the above advices tags contains "method" and "pointcut-ref" attributes, where "method" atribute will take advice method and "pointcut-ref" attribute will take Pointcut reference whic we declared in Configuration file.

Example54
JCode Cell
1 
2<beans xmlns="http://www.springframework.org/schema/beans"
3xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4xmlns:aop="http://www.springframework.org/schema/aop"
5xsi:schemaLocation="http://www.springframework.org/schema/beans
6http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
7http://www.springframework.org/schema/aop/
8http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
9 
10<aop:config>
11 
12<!-- Spring AOP Pointcut definitions -->
13<aop:pointcut id="loggingOperation"
14 expression="execution(* com.durgasoft.service.EmployeeService.*(..))" />
15 
16<!-- Spring AOP aspect -->
17<aop:aspect id="loggingAspect" ref="loggingAspectBean">
18 
19 <!-- Spring AOP advises -->
20 <aop:before pointcut-ref="loggingOperation" method="logBefore" />
21 <aop:after pointcut-ref="loggingOperation" method="logAfter" />
22 
23</aop:aspect>
24 
25 
26</aop:config>
27 
28<!-- Spring AOP aspect instances -->
29<bean id="loggingAspectBean" class="com.durgasoft.aspect.EmployeeCRUDLoggingAspect" />
30 
31<!-- Target Object -->
32<bean id="employeeManager" class="com.durgasoft.service.EmployeeServiceImpl" />
33 
34</beans>
35

Declaring Advices — Employee.java

Steps to prepare Application by using AspectJ namespace tags

  • Declare Beans.
  • Declare Service interface
  • Declare Service interface implementation class.
  • Create Aspect class
  • Prepare Spring Configuration file.
  • Prepare Test Application

Example On AOP namespace tags

Example55
JCode Cell
1 
2package com.durgasoft.beans;
3 
4public class Employee {
5private int eno;
6private String ename;
7private float esal;
8private String eaddr;
9 
10public int getEno() {
11return eno;
12}
13public void setEno(int eno) {
14this.eno = eno;
15}
16public String getEname() {
17return ename;
18}
19public void setEname(String ename) {
20this.ename = ename;
21}
22public float getEsal() {
23return esal;
24}
25public void setEsal(float esal) {
26this.esal = esal;
27}
28public String getEaddr() {
29return eaddr;
30}
31public void setEaddr(String eaddr) {
32this.eaddr = eaddr;
33}
34 
35 
36}
37

Declaring Advices — EmployeeService.java

Example56
JCode Cell
1 
2package com.durgasoft.service;
3 
4import com.durgasoft.beans.Employee;
5 
6public interface EmployeeService {
7public String createEmployee(Employee emp)throws Exception;
8public Employee searchEmployee(int eno);
9public String updateEmployee(Employee emp);
10public String deleteEmployee(Employee emp);
11}
12

Declaring Advices — EmployeeServiceImpl.java

Example57
JCode Cell
1 
2package com.durgasoft.service;
3 
4import com.durgasoft.beans.Employee;
5 
6public class EmployeeServiceImpl implements EmployeeService {
7 
8@Override
9public String createEmployee(Employee emp){
10 System.out.println("Employee "+emp.getEno()+" Inserted Successfully from createEmployee()");
11 
12return "Success";
13}
14 
15@Override
16public Employee searchEmployee(int eno) {
17System.out.println("Employee "+eno+" Existed from serachEmployee()");
18return null;
19}
20 
21@Override
22public String updateEmployee(Employee emp) {
23System.out.println("Employee "+emp.getEno()+" Updated Successfully from updateEmployee()");
24return "Success";
25}
26 
27@Override
28public String deleteEmployee(Employee emp) {
29System.out.println("Employee "+emp.getEno()+" Deleted Successfully from deleteEmployee()");
30return null;
31}
32 
33}
34

Declaring Advices — LoggingAspectBean.java

Example58
JCode Cell
1 
2package com.durgasoft.aspects;
3 
4import org.aspectj.lang.JoinPoint;
5import org.aspectj.lang.ProceedingJoinPoint;
6import org.aspectj.lang.annotation.After;
7import org.aspectj.lang.annotation.AfterReturning;
8import org.aspectj.lang.annotation.AfterThrowing;
9import org.aspectj.lang.annotation.Around;
10import org.aspectj.lang.annotation.Aspect;
11import org.aspectj.lang.annotation.Before;
12public class LoggingAspectBean {
13public void before(JoinPoint jp) {
14System.out.println("Before "+jp.getSignature().getName()+" method execution");
15}
16public void after(JoinPoint jp) {
17System.out.println("After "+jp.getSignature().getName()+" method execution");
18}
19public void afterReturning(JoinPoint jp, Object result) {
20System.out.println("After Returning "+result+" from "+jp.getSignature().getName());
21}
22public void around(ProceedingJoinPoint jp) {
23System.out.println("Before "+jp.getSignature().getName()+"execution from around Advice");
24try {
25 jp.proceed();
26} catch (Throwable e) {
27 e.printStackTrace();
28}
29System.out.println("After "+jp.getSignature().getName()+"execution from around Advice");
30}
31public void afterThrowing(JoinPoint jp, Throwable exception) {
32System.out.println("After throwing "+exception+" from "+jp.getSignature().getName()+" method");
33 
34}
35}
36

Declaring Advices — applicationContext.xml

Example59
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:aop="http://www.springframework.org/schema/aop"
6xsi:schemaLocation="
7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
8 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
9 
10<!-- beans -->
11<bean id="empBean" class="com.durgasoft.beans.Employee">
12<property name="eno" value="111"/>
13<property name="ename" value="AAA"/>
14<property name="esal" value="5000"/>
15<property name="eaddr" value="Hyd"/>
16</bean>
17<!-- target Bean-->
18<bean id="empService" class="com.durgasoft.service.EmployeeServiceImpl"/>
19 
20<!-- Aspect bean -->
21<bean id="loggingAspectBean" class="com.durgasoft.aspects.LoggingAspectBean"/>
22 
23<aop:config>
24<aop:aspect id="loggingAspect" ref="loggingAspectBean">
25<aop:pointcut expression="execution(* com.durgasoft.service.EmployeeService.*(..))" id="empPointcut"/>
26 
27<aop:before method="before" pointcut-ref="empPointcut"/>
28<aop:after method="after" pointcut-ref="empPointcut"/>
29<aop:after-returning method="afterReturning" pointcut-ref="empPointcut" returning="result"/>
30<aop:around method="around" pointcut-ref="empPointcut"/>
31 
32<aop:after-throwing method="afterThrowing" throwing="exception" pointcut-ref="empPointcut"/>
33</aop:aspect>
34</aop:config>
35 
36</beans>
37

Declaring Advices — Test.java

Example60
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.springframework.context.ApplicationContext;
5import org.springframework.context.support.ClassPathXmlApplicationContext;
6 
7import com.durgasoft.beans.Employee;
8import com.durgasoft.service.EmployeeService;
9 
10public class Test {
11public static void main(String[] args) {
12ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
13EmployeeService empService = (EmployeeService)context.getBean("empService");
14Employee emp = (Employee) context.getBean("empBean");
15String message = "";
16try {
17 message = empService.createEmployee(emp);
18} catch (Exception e) {
19 
20}
21System.out.println(message);
22}
23}
24

Declaring Advices — Show.java

Example:

Example61
JCode Cell
1 
2package com.durgasoft.beans;
3 
4public class Show {
5private String name;
6private String time;
7private int price;
8 
9public String getName() {
10 return name;
11}
12public void setName(String name) {
13this.name = name;
14}
15public String getTime() {
16return time;
17}
18public void setTime(String time) {
19this.time = time;
20}
21public int getPrice() {
22return price;
23}
24public void setPrice(int price) {
25this.price = price;
26}
27}
28

Declaring Advices — ShowService.java

Example62
JCode Cell
1 
2package com.durgasoft.service;
3 
4import com.durgasoft.beans.Show;
5 
6public interface ShowService {
7public String runShow(Show show)throws RuntimeException;
8}
9 
10ShowServiceImpl.java
11---------------------
12package com.durgasoft.service;
13 
14import com.durgasoft.beans.Show;
15 
16public class ShowServiceImpl implements ShowService {
17 
18@Override
19public String runShow(Show show)throws RuntimeException {
20System.out.println("******Show "+show.getName()+" Start****");
21System.out.println("Show "+show.getName()+" is Running Successfully");
22if(!show.getName().equalsIgnoreCase("Mimicry")) {
23 throw new RuntimeException();
24}
25System.out.println("******Show "+show.getName()+" End****");
26return "success";
27}
28}
29

Declaring Advices — ShowAspect.java

Example63
JCode Cell
1 
2package com.durgasoft.aspect;
3 
4import org.aspectj.lang.ProceedingJoinPoint;
5 
6public class ShowAspect {
7public void before() {
8 System.out.println("Get Tickets for the Show");
9}
10public void around(ProceedingJoinPoint jp) {
11System.out.println("Show is Ready To start, Take Chairs and Keep mobiles in Silent mode");
12try {
13 jp.proceed();
14} catch (Throwable e) {
15 e.printStackTrace();
16}
17System.out.println("Show Completed just now, Check your Laguages");
18}
19public void after() {
20System.out.println("Show is over , quit from Hall");
21}
22public void afterReturning() {
23System.out.println("Tankq for attending Show");
24}
25 
26public void afterThrowing() {
27System.out.println("There is an Interruption in show, because, Show is not Mimicry show");
28}
29}
30

Declaring Advices — applicationContext.xml

Example64
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:aop="http://www.springframework.org/schema/aop"
6xsi:schemaLocation="
7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
8 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
9<!-- beans -->
10<bean id="showBean" class="com.durgasoft.beans.Show">
11<property name="name" value="Singing"/>
12<property name="time" value="7:30PM"/>
13<property name="price" value="1000"/>
14</bean>
15 
16 
17<!-- Target -->
18<bean id="showService" class="com.durgasoft.service.ShowServiceImpl"/>
19 
20<!-- aspect -->
21<bean id="showAspect" class="com.durgasoft.aspect.ShowAspect"/>
22 
23<aop:config>
24<aop:aspect id="mimicryShowAspect" ref="showAspect">
25 <aop:pointcut expression="execution(public String com.durgasoft.service.ShowService.runShow(com.durgasoft.beans.Show))" id="showPointcut"/>
26 
27 <aop:before method="before" pointcut-ref="showPointcut"/>
28 <!-- <aop:around method="around" pointcut-ref="showPointcut"/> -->
29 <aop:after method="after" pointcut-ref="showPointcut"/>
30 <aop:after-returning method="afterReturning" pointcut-ref="showPointcut"/>
31 <aop:after-throwing method="afterThrowing" pointcut-ref="showPointcut" />
32</aop:aspect>
33</aop:config>
34</beans>
35

Declaring Advices — Test.java

Example65
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.springframework.context.ApplicationContext;
5import org.springframework.context.support.ClassPathXmlApplicationContext;
6 
7import com.durgasoft.beans.Show;
8import com.durgasoft.service.ShowService;
9 
10public class Test {
11 
12public static void main(String[] args) {
13ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
14Show show = (Show) context.getBean("showBean");
15ShowService showService = (ShowService) context.getBean("showService");
16try {
17 showService.runShow(show);
18} catch (RuntimeException e) {
19 //System.out.println(e.getMessage());
20}
21}
22}
23

@AspectJ annotation style approach

Spring Framework supporting Annotations to support AspectJ implementation in the form of "org.aspectj.lang.annotation" package.

Spring AspectJ AOP implementation provides the following annotations — Account.java

  • @Aspect: It will declare a class as an aspect. actual
  • @Pointcut: It will declare a pointcut expression.
  • @Before: It will declare before advice, It will be executed before executing the

Business method.

  • @After: It will declare after advice, It will be executed after executing the actual Business

method and before returning result.

  • @AfterReturning: It declares after returning advice, It will be executed after calling the

actual Business method and after returning result.

  • @Around: It declares around advice, It will be executed before and after calling the actual

Business method.

  • @AfterThrowing: It declares the throws advice, It will be executed if the actual Business

method throws exception.

Note: To activate all the above annotations in Spring applications we have to use <aop:aspectj- autoproxy/> tag in spring configuration file.

Example:

Example67
JCode Cell
1 
2package com.durgasoft.beans;
3 
4public class Account {
5private String accNo;
6private String accName;
7private String accType;
8private int balance;
9 
10public String getAccNo() {
11return accNo;
12}
13public void setAccNo(String accNo) {
14this.accNo = accNo;
15}
16public String getAccName() {
17return accName;
18}
19public void setAccName(String accName) {
20this.accName = accName;
21}
22public String getAccType() {
23return accType;
24}
25public void setAccType(String accType) {
26this.accType = accType;
27}
28public int getBalance() {
29return balance;
30}
31public void setBalance(int balance) {
32this.balance = balance;
33}
34 
35 
36}
37

Spring AspectJ AOP implementation provides the following annotations — TransactionService.java

Example68
JCode Cell
1 
2package com.durgasoft.service;
3 
4import com.durgasoft.beans.Account;
5import com.durgasoft.exceptions.InsufficientFundsException;
6 
7public interface TransactionService {
8public String withdraw(Account acc, int wd_Amt)throws InsufficientFundsException;
9}
10

Spring AspectJ AOP implementation provides the following annotations — TransactionServiceImpl.java

Example69
JCode Cell
1 
2package com.durgasoft.service;
3 
4import org.springframework.stereotype.Component;
5 
6import com.durgasoft.beans.Account;
7import com.durgasoft.exceptions.InsufficientFundsException;
8 
9@Component("transaction")
10public class TransactionServiceImpl implements TransactionService {
11 
12@Override
13public String withdraw(Account acc, int wd_Amt) throws InsufficientFundsException {
14String status = "";
15if(acc.getBalance() > wd_Amt) {
16int total_Bal = acc.getBalance() - wd_Amt;
17acc.setBalance(total_Bal);
18System.out.println("From withdraw(): Transaction Withdraw Completed ");
19status = "SUCCESS";
20}else {
21 status = "FAILURE";
22 throw new InsufficientFundsException("Funds are not Sufficient in Account");
23}
24return status;
25}
26}
27

Spring AspectJ AOP implementation provides the following annotations — InsufficientFundsException.java

Example70
JCode Cell
1 
2package com.durgasoft.exceptions;
3 
4public class InsufficientFundsException extends Exception {
5public InsufficientFundsException(String desc) {
6 super(desc);
7}
8}
9

Spring AspectJ AOP implementation provides the following annotations — TransactionAspect.java

Example71
JCode Cell
1 
2package com.durgasoft.aspect;
3 
4import org.aspectj.lang.JoinPoint;
5import org.aspectj.lang.ProceedingJoinPoint;
6import org.aspectj.lang.annotation.After;
7import org.aspectj.lang.annotation.AfterReturning;
8import org.aspectj.lang.annotation.AfterThrowing;
9import org.aspectj.lang.annotation.Around;
10import org.aspectj.lang.annotation.Aspect;
11import org.aspectj.lang.annotation.Before;
12import org.springframework.stereotype.Component;
13 
14import com.durgasoft.beans.Account;
15import com.durgasoft.exceptions.InsufficientFundsException;
16@Component("aspect")
17@Aspect
18public class TransactionAspect {
19@Before("execution(* com.durgasoft.service.TransactionService.*(..))")
20public void before(JoinPoint jp) {
21Object[] args = jp.getArgs();
22Account acc = (Account) args[0];
23System.out.println("Before Advice : Initial Balance :"+acc.getBalance());
24}
25 
26@After("execution(* com.durgasoft.service.TransactionService.*(..))")
27public void after(JoinPoint jp) {
28Object[] args = jp.getArgs();
29Account acc = (Account) args[0];
30System.out.println("After Advice : Total Balance :"+acc.getBalance());
31}
32 
33@AfterReturning(pointcut="execution(* com.durgasoft.service.TransactionService.*(..))",
34 returning="result")
35public void afterReturning(JoinPoint jp, String result) {
36System.out.println("After Returning Advice: Transaction Status :"+result);
37}
38 
39@Around("execution(* com.durgasoft.service.TransactionService.*(..))")
40public void around(ProceedingJoinPoint jp) {
41System.out.println("Around Advice : Before "+jp.getSignature().getName()+" Method Execution");
42String status = "";
43try {
44 status = (String)jp.proceed();
45} catch (Throwable e) {
46 e.printStackTrace();
47}
48System.out.println("Around Advice : After "+jp.getSignature().getName()+" Method Execution");
49System.out.println("Around Advice : Transaction Status :"+status);
50}
51 
52//@AfterThrowing(pointcut="execution(* com.durgasoft.service.TransactionService.*(..))",
53 //throwing="exception")
54public void afterThrowing(JoinPoint jp, InsufficientFundsException exception) {
55System.out.println("After Throwing Advice : "+exception.getClass().getName()+" In Transaction :"+exception.getMessage());
56}
57}
58

Spring AspectJ AOP implementation provides the following annotations — applicationContext.xml

Example72
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!--
4<beans xmlns="http://www.springframework.org/schema/beans"
5xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
6xmlns:aop="http://www.springframework.org/schema/aop"
7xsi:schemaLocation="
8 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
9 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
10-->
11 
12<beans xmlns="http://www.springframework.org/schema/beans"
13xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
14xmlns:aop="http://www.springframework.org/schema/aop"
15xmlns:context="http://www.springframework.org/schema/context"
16xsi:schemaLocation="
17http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
18http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
19http://www.springframework.org/schema/context
20http://www.springframework.org/schema/context/spring-context.xsd">
21 
22<context:annotation-config/>
23<context:component-scan base-package="com.durgasoft.service"/>
24<context:component-scan base-package="com.durgasoft.aspect"/>
25<aop:aspectj-autoproxy/>
26<!-- beans -->
27<bean id="accBean" class="com.durgasoft.beans.Account">
28<property name="accNo" value="abc123"/>
29<property name="accName" value="Durga"/>
30<property name="accType" value="Savings"/>
31<property name="balance" value="20000"/>
32</bean>
33<!--
34 
35<bean id="transaction" class="com.durgasoft.service.TransactionServiceImpl"/>
36 
37 
38<bean id="txAspect" class="com.durgasoft.aspect.TransactionAspect"/>
39-->
40</beans>
41

Spring AspectJ AOP implementation provides the following annotations — Test.java

Example73
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.springframework.context.ApplicationContext;
5import org.springframework.context.support.ClassPathXmlApplicationContext;
6 
7import com.durgasoft.beans.Account;
8import com.durgasoft.exceptions.InsufficientFundsException;
9import com.durgasoft.service.TransactionService;
10 
11public class Test {
12 
13public static void main(String[] args) {
14ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
15Account acc = (Account) context.getBean("accBean");
16TransactionService txService = (TransactionService) context.getBean("transaction");
17try {
18 txService.withdraw(acc,50000);
19} catch (InsufficientFundsException e) {
20 //e.printStackTrace();
21}
22 
23}
24}
25
📝 Key Takeaways
  • Key ideas of Spring - AOP (Aspect Oriented Programming) explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end