Spring AOP

Spring AOP:

Aspect Oriented Programming (AOP) compliments OOPs as in it additionally gives particularity. Be that as it may, the key unit of seclusion is angle than class. AOP breaks the program rationale into unmistakable parts (called concerns). It is utilized to build particularity by cross-cutting concerns.

A cross-cutting concern is a worry that can influence the entire application and ought to be brought together in one area in code as could be allowed, for example, exchange administration, confirmation, logging, security.

There are 5 techniques that begins from m, 2 strategies that begins from n and 3 strategies that begins from p.

Understanding Scenario I need to keep up log and send warning in the wake of calling strategies that begins from m.

Issue without AOP We can call techniques (that keeps up log and sends notice) from the strategies beginning with m. In such situation, we have to compose the code in all the 5 strategies.

AOP Concepts and Terminology
  • Join point
  • Advice
  • Pointcut
  • Introduction
  • Target Object
  • Aspect
  • Interceptor
  • AOP Proxy
  • Weaving

AOP Implementations

  1. AspectJ
  2. Spring AOP
  3. JBoss AOP

Spring AOP Example There are given instances of Spring1.2 old style AOP (dtd based) execution. Disregarding the way that it is supported in spring 3, yet it is recommended to use spring AOP.

There are 4 sorts of advices maintained in spring1.2 old style aop utilization.
  1. Before Advice
  2. After Advice
  3. Around Advice
  4. Throws Advice

hierarchy of advice interfaces:

AOP HierarchyMethodBeforeAdvice interface extends the BeforeAdvice interface.

AfterReturningAdvice interface extends the AfterAdvice interface.

ThrowsAdvice interface extends the AfterAdvice interface.

MethodInterceptor interface extends the Interceptor interface. It is used in around advice.

AOP AspectJ Annotation:

The Spring Framework prescribes you to utilize Spring AspectJ AOP execution over the Spring 1.2 old style dtd based AOP usage since it gives you more control.

  1. By annotation: We are going to learn it here.
  2. By xml configuration (schema based)
Understanding Pointcut:

The @Pointcut comment is utilized to characterize the pointcut. We can allude the pointcut articulation by name too. How about we see the straightforward case of pointcut articulation.

@Pointcut(“execution(* Operation.*(..))”)

private void doSomething() {}

Understanding Pointcut Expressions

@Pointcut(“execution(public * *(..))”)

@Pointcut(“execution(public Operation.*(..))”)

@Pointcut(“execution(* Operation.*(..))”)

@Pointcut(“execution(public Employee.set*(..))”)

@Pointcut(“execution(int Operation.*(..))”)

AOP AspectJ Xml Configuration

Spring empowers you to characterize the perspectives, advices and pointcut in xml record. In the past page, we have seen the AOP cases utilizing explanations. Presently we will see same cases by the xml design record.

  1. aop:before
  2. aop:after
  3. aop:after-returning
  4. aop:around
  5. aop:after-throwing
aop:before Example
 File: Operation.java

package com.javatspot;

public  class Operation{

public void msg(){System.out.println(“msg method invoked”);}

public int m(){System.out.println(“m method invoked”);return 2;}

public int k(){System.out.println(“k method invoked”);return 3;}

}

 

File: TrackOperation.java

package com.javaspot;

import org.aspectj.lang.JoinPoint;

public class TrackOperation{

public void myadvice(JoinPoint jp)//it is advice

{

System.out.println(“additional concern”);

//System.out.println(“Method Signature: ”  + jp.getSignature());

}

}

 File: applicationContext.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

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

xmlns:xsi=”http://www.w3.org/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-3.0.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd “>

<aop:aspectj-autoproxy />

<bean id=”opBean” class=”com.javaspot.Operation”>   </bean>

<bean id=”trackAspect” class=”com.javaspot.TrackOperation”></bean>

<aop:config>

<aop:aspect id=”myaspect” ref=”trackAspect” >

<!– @Before –>

<aop:pointcut id=”pointCutBefore”   expression=”execution(* com.javaspot.Operation.*     (..))” />

<aop:before method=”myadvice” pointcut-ref=”pointCutBefore” />

</aop:aspect>

</aop:config>

</beans>

.File: Test.java

package com.javaspot;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test{

public static void main(String[] args){

ApplicationContext context = new ClassPathXmlApplicationContext(“applicationContext.xml”);

Operation e = (Operation) context.getBean(“opBean”);

System.out.println(“calling msg…”);

e.msg();

System.out.println(“calling m…”);

e.m();

System.out.println(“calling k…”);

e.k();

}

}

Output

calling msg…

additional concern

msg() method invoked

calling m…

additional concern

m() method invoked

calling k…

additional concern

k() method invoked

2) aop:after example

 File: applicationContext.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

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

xmlns:xsi=”http://www.w3.org/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-3.0.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd “>

<aop:aspectj-autoproxy />

<bean id=”opBean” class=”com.javatpoint.Operation”>   </bean>

<bean id=”trackAspect” class=”com.javatpoint.TrackOperation”></bean>

<aop:config>

<aop:aspect id=”myaspect” ref=”trackAspect” >

<!– @After –>

<aop:pointcut id=”pointCutAfter”    expression=”execution(* com.javatpoint.Operation.*(..))” />

<aop:after method=”myadvice” pointcut-ref=”pointCutAfter” />

</aop:aspect>

</aop:config>

</beans>

Output

calling msg…

msg() method invoked

additional concern

calling m…

m() method invoked

additional concern

calling k…

k() method invoked

additional concern

 3) aop:after-returning example

 File: Operation.java

package com.javaspot;

public  class Operation{

public int m(){System.out.println(“m() method invoked”);return 2;}

public int k(){System.out.println(“k() method invoked”);return 3;}

}

Create the aspect class that contains after returning advice.

File: TrackOperation.java

package com.javaspot;

import org.aspectj.lang.JoinPoint;

public class TrackOperation{

public void myadvice(JoinPoint jp,Object result)//it is advice (after advice)

{

System.out.println(“additional concern”);

System.out.println(“Method Signature: ”  + jp.getSignature());

System.out.println(“Result in advice: “+result);

System.out.println(“end of after returning advice…”);

}

}

 File: applicationContext.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

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

xmlns:xsi=”http://www.w3.org/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-3.0.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd “>

<aop:aspectj-autoproxy />  <bean id=”opBean” class=”com.javaspot.Operation”>   </bean>

<bean id=”trackAspect” class=”com.javaspot.TrackOperation”></bean>

<aop:config>

<aop:aspect id=”myaspect” ref=”trackAspect” >

<!– @AfterReturning –>

<aop:pointcut id=”pointCutAfterReturning”   expression=”execution(* com.javaspot.Operation.*(..))” />

<aop:after-returning method=”myadvice” returning=”result” pointcut-ref=”pointCutAfterReturning” />

</aop:aspect>

</aop:config>

</beans>

 File: Test.java

package com.javaspot;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test{

public static void main(String[] args){

ApplicationContext context = new ClassPathXmlApplicationContext(“applicationContext.xml”);

Operation e = (Operation) context.getBean(“opBean”);

System.out.println(“calling m…”);

System.out.println(e.m());

System.out.println(“calling k…”);

System.out.println(e.k());

}

}

 Output

calling m…

m() method invoked

additional concern

Method Signature: int com.javaspot.Operation.m()

Result in advice: 2

end of after returning advice…

2

calling k…

k() method invoked

additional concern

Method Signature: int com.javaspot.Operation.k()

Result in advice: 3

end of after returning advice…

3

4) aop:around example

The AspectJ around advice is applied before and after calling the actual business logic methods.

Create a class that contains actual business logic.

File: Operation.java

package com.javaspot;

public  class Operation{

public void msg(){System.out.println(“msg() is invoked”);}

public void display(){System.out.println(“display() is invoked”);}

}

.File: TrackOperation.java

package com.javaspot;

import org.aspectj.lang.ProceedingJoinPoint;

public class TrackOperation

{

public Object myadvice(ProceedingJoinPoint pjp) throws Throwable

{

System.out.println(“Additional Concern Before calling actual method”);

Object obj=pjp.proceed();

System.out.println(“Additional Concern After calling actual method”);

return obj;

}

}

 File: applicationContext.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

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

xmlns:xsi=”http://www.w3.org/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-3.0.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd “>

<aop:aspectj-autoproxy />

<bean id=”opBean” class=”com.javaspot.Operation”>   </bean>

<bean id=”trackAspect” class=”com.javaspot.TrackOperation”></bean>

<aop:config>

<aop:aspect id=”myaspect” ref=”trackAspect” >

<!– @Around –>

<aop:pointcut id=”pointCutAround”   expression=”execution(* com.javaspot.Operation.*(..))” />

<aop:around method=”myadvice” pointcut-ref=”pointCutAround” />

</aop:aspect>

</aop:config>

</beans>

 File: Test.java

package com.javaspot;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test{

public static void main(String[] args){

ApplicationContext context = new classPathXmlApplicationContext(“applicationContext.xml”);

Operation op = (Operation) context.getBean(“opBean”);

op.msg();

op.display();

}

}

Output

Additional Concern Before calling actual method

msg() is invoked

Additional Concern After calling actual method

Additional Concern Before calling actual method

display() is invoked

Additional Concern After calling actual method

 5) aop:after-throwing example

 File: Operation.java

package com.javaspot;

public  class Operation{

public void validate(int age)throws Exception{

if(age<18){

throw new ArithmeticException(“Not valid age”);

}

else{

System.out.println(“Thanks for vote”);

}

}

}

 File: TrackOperation.java

package com.javaspot;

import org.aspectj.lang.JoinPoint;

public class TrackOperation{

public void myadvice(JoinPoint jp,Throwable error)//it is advice

{

System.out.println(“additional concern”);

System.out.println(“Method Signature: ”  + jp.getSignature());

System.out.println(“Exception is: “+error);

System.out.println(“end of after throwing advice…”);

}

}

File: applicationContext.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

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

xmlns:xsi=”http://www.w3.org/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-3.0.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd “>

<aop:aspectj-autoproxy />

<bean id=”opBean” class=”com.javaspot.Operation”>   </bean>

<bean id=”trackAspect” class=”com.javaspot.TrackOperation”></bean>

<aop:config>

<aop:aspect id=”myaspect” ref=”trackAspect” >

<!– @AfterThrowing –>

<aop:pointcut id=”pointCutAfterThrowing”    expression=”execution(* com.javaspot.Operation.*(..))” />

<aop:after-throwing method=”myadvice” throwing=”error” pointcut-ref=”pointCutAfterThrowing” />

</aop:aspect>

</aop:config>

</beans>

 File: Test.java

package com.javaspot;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test{

public static void main(String[] args){

ApplicationContext context = new ClassPathXmlApplicationContext(“applicationContext.xml”);

Operation op = (Operation) context.getBean(“opBean”);

System.out.println(“calling validate…”);

try{

op.validate(19);

}catch(Exception e){System.out.println(e);}

System.out.println(“calling validate again…”);

try{

op.validate(11);

}catch(Exception e){System.out.println(e);}

}

}

Output

calling validate…

Thanks for vote

calling validate again…

additional concern

Method Signature: void com.javaspot.Operation.validate(int)

Exception is: java.lang.ArithmeticException: Not valid age

end of after throwing advice…

java.lang.ArithmeticException: Not valid age

 JdbcTemplate:

Spring JdbcTemplate is an effective instrument to associate with the database and execute SQL inquiries. It inside utilizations JDBC programming interface, however dispenses with a great deal of issues of JDBC API.

Issues of JDBC API

The issues of JDBC API are as per the following:

We have to compose a ton of code previously, then after the fact executing the question, for example, making association, proclamation, shutting resultset, association and so forth.

We have to perform special case taking care of code on the database logic.

We have to deal with exchange. Reiteration of every one of these codes starting with one then onto the next database rationale is a tedious assignment.

Preferred standpoint of Spring JdbcTemplate

Spring JdbcTemplate wipes out all the previously mentioned issues of JDBC API. It gives you strategies to compose the inquiries straightforwardly, so it spares a great deal of work and time.

Spring Jdbc Approaches
  • JdbcTemplate
  • NamedParameterJdbcTemplate
  • SimpleJdbcTemplate
  • SimpleJdbcInsert and SimpleJdbcCall
JdbcTemplate class

It is the focal class in the Spring JDBC bolster classes. It deals with creation and arrival of assets, for example, making and shutting of association question and so forth. So it won’t prompt any issue on the off chance that you neglect to close the association.

It handles the special case and gives the useful exemption messages by the assistance of excepion classes characterized in the org.springframework.dao bundle. We can play out all the database operations by the assistance of JdbcTemplate class, for example, addition, updation, cancellation and recovery of the information from the database.

No. Method
1) public int update(String query)
2) public int update(String query,Object… args)
3) public void execute(String query)
4) public Texecute(Stringsql, PreparedStatementCallback action)
5) public T query(String sql, ResultSetExtractorrse)
6) public List query(String sql, RowMapper rse)
PreparedStatement in Spring JdbcTemplate:
Syntax :
public T execute(String sql,PreparedStatementCallback<T>);
PreparedStatementCallback interface

The input parameters and output results, you don’t need to care about single and double quotes.

Method of PreparedStatementCallback interface

It has only one method doInPreparedStatement

  1. publicT doInPreparedStatement(PreparedStatement ps)throws SQLException, DataAccessException
 ResultSetExtractor

We can without much of a stretch get the records from the database utilizing inquiry() strategy for JdbcTemplate class where we have to pass the example of ResultSetExtractor.

Syntax

  1. publicT query(String sql,ResultSetExtractor<T> rse)  

ResultSetExtractor Interface

 ResultSetExtractor interface can be utilized to get records from the database. It acknowledges a ResultSet and returns the rundown.

Strategy for ResultSetExtractor interface

 It characterizes just a single strategy extractData that acknowledges ResultSet case as a parameter.

  1. publicT extractData(ResultSet rs)throws SQLException,DataAccessException  
 RowMapper

Syntax

  1. publicT query(String sql,RowMapper<T> rm)

RowMapper Interface

RowMapper interface permits to delineate column of the relations with the occasion of client characterized class. It emphasizes the ResultSet inside and includes it into the accumulation. So we don’t have to compose a considerable measure of code to bring the records as ResultSetExtractor.

Advantage:

RowMapper spares a ton of code becuase it inside includes the information of ResultSet into the accumulation.

Strategy for RowMapper interface :

It characterizes just a single technique mapRow that acknowledges ResultSet occurrence and int as the parameter list. Sentence structure of the strategy is given beneath.

  1. publicT mapRow(ResultSet rs, int rowNumber)throws SQLException  
 Spring NamedParameterJdbcTemplate

Spring gives another approach to embed information by named parameter. In such way, we utilize names rather than ?(question mark). So it is smarter to recall the information for the segment.

Basic case of named parameter inquiry

insert into employee values (:id,:name,:salary)  

Strategy for NamedParameterJdbcTemplate class

In this example,we will call just the execute strategy for NamedParameterJdbcTemplate class. Grammar of the technique is as take after.

Spring SimpleJdbcTemplate

spring 3 JDBC underpins the java 5 highlight var-args (variable contention) and autoboxing by the assistance of SimpleJdbcTemplate class.

SimpleJdbcTemplate class wraps the JdbcTemplate class and gives the refresh technique where we can pass subjective number of contentions.

Syntax of update method of SimpleJdbcTemplate class

  1. intupdate(String sql,Object… parameters)

 Example of SimpleJdbcTemplate class

create table employee(

id number(10),

name varchar2(100),

salary number(10)

);

 Employee.java

package com.javaspot;

public class Employee {

private int id;

private String name;

private float salary;

//no-arg and parameterized constructors

//getters and setters

}

 EmployeeDao.java

package com.javaspot;

import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

public class EmpDao {

SimpleJdbcTemplate template;

public EmpDao(SimpleJdbcTemplate template) {

this.template = template;

}

public int update (Emp e){

String query=”update employee set name=? where id=?”;

return template.update(query,e.getName(),e.getId());

//String query=”update employee set name=?,salary=? where id=?”;

//return template.update(query,e.getName(),e.getSalary(),e.getId());

}

 

}

 applicationContext.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<beans

xmlns=”http://www.springframework.org/schema/beans”

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

xmlns:p=”http://www.springframework.org/schema/p”

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

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”>

<bean id=”ds” class=”org.springframework.jdbc.datasource.DriverManagerDataSource”>

<property name=”driverClassName” value=”oracle.jdbc.driver.OracleDriver” />

<property name=”url” value=”jdbc:oracle:thin:@localhost:1521:xe” />

<property name=”username” value=”system” />

<property name=”password” value=”oracle” />

</bean>

<bean id=”jtemplate” class=”org.springframework.jdbc.core.simple.SimpleJdbcTemplate”>

<constructor-arg ref=”ds”></constructor-arg>

</bean>

<bean id=”edao” class=”com.javaspot.EmpDao”>

<constructor-arg>

<ref bean=”jtemplate”/>

</constructor-arg>

</bean>

</beans>

 SimpleTest.java

package com.javaspot;

import org.springframework.beans.factory.BeanFactory;

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

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.Resource;

public class SimpleTest {

public static void main(String[] args) {

Resource r=new ClassPathResource(“applicationContext.xml”);

BeanFactory factory=new XmlBeanFactory(r);

EmpDao dao=(EmpDao)factory.getBean(“edao”);

int status=dao.update(new Emp(23,”Tarun”,35000));

System.out.println(status);

}

}

Drop Us A Query

Trending Courses
  • Python and Django Online Training
  • Python is a dynamic interrupted language which is used in wide varieties of applications. It is very interactive object oriented and high-level programming language.

  • Tableau Online Training
  • Tableau is a Software company that caters interactive data visualization products that provide Business Intelligence services. The company’s Head Quarters is in Seattle, USA.

  • MicroStrategy Online Training
  • Micro Strategy is one of the few independent and publicly trading Business Intelligence software provider in the market. The firm is operational in 27 Countries around the globe.

  • PEGA (PRPC) 7.2 Certification Online Training
  • Pega Systems Inc. is a Cambridge, Massachusetts based Software Company. It is known for developing software for Customer Relationship Management (CRM) and Business process Management (BPM).

  • Workday Online Training
  • Workday specialises in providing Human Capital Management, Financial Management and payroll in online domain.It is a major web based ERP software vendor.

  • Power BI Online Training
  • Power BI is business analytics service by Microsoft. With Power BI, end users can develop reports and dashboards without depending on IT staff or Database Administrator.


100% Secure Payments. All major credit & debit cards accepted.