Log In to start Learning

Login via

Post By Admin Last Updated At 2020-06-15
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. Spring 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.To get in-depth knowledge on Java, you can enroll for live Java online course by OnlineITGuru with 24/7 support and lifetime accessUnderstanding Scenario I need to keep up log and send warning in the wake of calling strategies that begins 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.javapackage 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.xmlclass="com.javaspot.Operation">   class="com.javaspot.TrackOperation">.File: Test.javapackage 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();}}


calling msg...additional concernmsg() method invokedcalling m...additional concernm() method invokedcalling k...additional concernk() method invoked2) aop:after example File: applicationContext.xmlclass="com.javatpoint.Operation">   class="com.javatpoint.TrackOperation">
calling msg...msg() method invokedadditional concerncalling m...m() method invokedadditional concerncalling k...k() method invokedadditional concern

 3) aop:after-returning example

 File: Operation.javapackage 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.javapackage 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  class="com.javaspot.Operation">   class="com.javaspot.TrackOperation"> File: Test.javapackage 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());}}
calling m...m() method invokedadditional concernMethod Signature: int com.javaspot.Operation.m()Result in advice: 2end of after returning advice...2calling k...k() method invokedadditional concernMethod Signature: int com.javaspot.Operation.k()Result in advice: 3end 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.javapackage 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.javapackage 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.xmlclass="com.javaspot.Operation">   class="com.javaspot.TrackOperation"> File: Test.javapackage 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();}}


Additional Concern Before calling actual methodmsg() is invokedAdditional Concern After calling actual methodAdditional Concern Before calling actual methoddisplay() is invokedAdditional Concern After calling actual method 5) aop:after-throwing example File: Operation.javapackage 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.javapackage 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.xmlclass="com.javaspot.Operation">   class="com.javaspot.TrackOperation"> File: Test.javapackage 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);}}}


calling validate...Thanks for votecalling validate again...additional concernMethod Signature: void com.javaspot.Operation.validate(int)Exception is: java.lang.ArithmeticException: Not valid ageend of after throwing advice...java.lang.ArithmeticException: Not valid age
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 APIThe 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.
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);
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
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 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  


  1. publicT query(String sql,RowMapper rm)
RowMapper InterfaceRowMapper 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 inquiryinsert into employee values (:id,:name,:salary)  Strategy for NamedParameterJdbcTemplate classIn 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 classcreate table employee(id number(10),name varchar2(100),salary number(10)); Employee.javapackage com.javaspot;public class Employee {private int id;private String name;private float salary;//no-arg and parameterized constructors//getters and setters} EmployeeDao.javapackage 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.xmlclass="org.springframework.jdbc.datasource.DriverManagerDataSource">class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">class="com.javaspot.EmpDao"> SimpleTest.javapackage 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);}}