Friday 23 October 2015

Spring Transaction with annotation for Spring JDBC


Step-1
  <!-- 
        Spring is doing jndi lookup to access the connection pool manage by our server
        jndi is service running on server.
   -->

 <jee:jndi-lookup id="bankDataSource" jndi-name="jdbc/synergy-bank-ds"/>

  "bankDataSource"  is pointing to the database connection. means we can communicate with database using bankDataSource.


Step-2
Create spring transaction manager for spring jdbc 

<!--
DataSourceTransactionManager class comes from spring jdbc module
-->

 <!-- Creating TransactionManager Bean, since JDBC we are creating of type 
DataSourceTransactionManager -->
<bean id="jdbctransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
   <property name="dataSource" ref="bankDataSource" />

</bean>

Step-3
Associating above transaction  manager with annotation...........
@Transactional


<tx:annotation-driven  proxy-target-class="true" transaction-manager="jdbctransactionManager"/>



Step-4
Applying above transaction manager  inside the dao layer
@Repository("BankAdminDaoImpl")
@Scope("singleton")
@Transactional(propagation=Propagation.REQUIRED)
public class BankAdminDaoImpl extends JdbcDaoSupport implements BankAdminDao{

@Autowired
@Qualifier("bankDataSource")
// here we are injecting bankDataSource inside JdbcDaoSupport super class
public void setDataSourceInBank(DataSource dataSource) {
super.setDataSource(dataSource);
}


@Override
public List<CustomerEntity> findPendingCustomerList(){
List<CustomerEntity> customerList = super.getJdbcTemplate().query(AdminQuery.FIND_PENDING_CUSTOMER_LIST,
new BeanPropertyRowMapper<CustomerEntity>(CustomerEntity.class));
return customerList;
}

P.S. - > Spring Declarative Transaction is based on AOP..

How to know spring transaction is working or not..............??

boolean action=TransactionSynchronizationManager.isActualTransactionActive();

-------------------------------------------------------------------------------------------
action - true means spring transaction is enabled inside this method

Files involves in spring transaction for spring jdbc
1. synergyDataSource.xml
2. BankAdminDaoImpl.java



Wednesday 7 October 2015

Implementing AOP with aspectJ

Step-1
                                      <!-- Using AOP with aspectJ -->
                   <dependency>
                             <groupId>org.aspectj</groupId>
                             <artifactId>aspectjrt</artifactId>
                             <version>1.6.11</version>
                   </dependency>

                   <dependency>
                             <groupId>org.aspectj</groupId>
                             <artifactId>aspectjweaver</artifactId>
                             <version>1.6.11</version>
                   </dependency>


Step-2
Enabling aspectJ annotation
apna-aop.xml

 <!-- We have concept for Proxy object for implementing AOP
         two kind of proxy
         1. Java Dynamic Proxy(proxy-target-class="false")
         2. CGLIB Proxy(proxy-target-class="true") 
     -->
        <!-- this will enable aspectJ annotation -->
   <aop:aspectj-autoproxy proxy-target-class="false"/>

 Step-3
 scan the package where advice class present  
   <!-- This is package name where our advice resides -->
   <context:component-scan base-package="com.apna.bank.aop"/>


Step-4
Define Advice using aspectJ annoation

@Aspect
@Component("apnaStartingTimeAdvice")
public class ApnaStartingTimeAdvice {

}

Step-5
define the point cut

Note: 
Pointcut: Pointcut are expressions that is matched with join points to determine whether advice needs to be executed or not. Pointcut uses different kinds of expressions that are matched with the join points and Spring framework uses the AspectJ pointcut expression language.

   @Before("execution(* com.apna.bank.dao.impl.*.*(..))")
   public void logBeforeTime(JoinPoint joinPoint) {
              System.out.println("Name of the method " + joinPoint.getSignature().getName());
             Date cdate=new Date();
             System.out.println("++++Current Date is  = "+cdate);
            System.out.println("___________________________________");
   }


@Before("execution(public String getName())")
public void getNameAdvice(){
        System.out.println("Executing Advice on getName()");
}
     

@Before("execution(* com.abc.spring.service.*.get*())")
public void getAllAdvice(){
      System.out.println("Service method getter called");
}


   Pointcut Methods and Reuse:-


//Pointcut to execute on all the methods of classes in a package
@Pointcut("within(com.abc.spring.service.*)")
public void allMethodsPointcut(){}


@Before("allMethodsPointcut()")
public void allServiceMethodsAdvice(){
        System.out.println("Before executing service method");
}


JoinPoint and Advice Arguments
@Aspect
public class EmployeeAspectJoinPoint {

 @Before("execution(public void com.spring.model..set*(*))")
  public void loggingAdvice(JoinPoint joinPoint){
  System.out.println("Before running loggingAdvice on method="+
joinPoint.toString());
       System.out.println("Agruments Passed="
Arrays.toString(joinPoint.getArgs()));
 
    }
     
    //Advice arguments, will be applied to bean methods with single String argument
    @Before("args(name)")
    public void logStringArguments(String name){
        System.out.println("String argument passed="+name);
    }
}

After Advice Example:-

@Aspect
public class EmployeeAfterAspect {
 
    @After("args(name)")
    public void logStringArguments(String name){
    System.out.println("Running After Advice. String argument
passed="+name);
    }
     
   @AfterThrowing("within(com.spring.model.Employee)")
    public void logExceptions(JoinPoint joinPoint){
       System.out.println("Exception thrown in Employee Method="+
joinPoint.toString());
    }
     
   @AfterReturning(pointcut="execution(* getName())"
returning="returnString")
    public void getNameReturningAdvice(String returnString){
        System.out.println("getNameReturningAdvice 
executed. Returned String="+returnString);
    }
     
}



Advice with Custom Annotation Pointcut :-

  Loggable.java

package com.spring.aspect;

public @interface Loggable {
 
}




package com.spring.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
 
@Aspect
public class EmployeeAnnotationAspect {
 
   @Before("@annotation(com.spring.aspect.Loggable)")
    public void myAdvice(){
        System.out.println("Executing myAdvice!!");
    }
}



@Repository
class CustomerDao implements ICustomerDao {

@Loggable
public void cool(){

}

}