Friday 18 December 2015

Java Method Logging with AOP and Annotations

Step-1

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>

<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

Enable AOP Annotations

    <!-- this will enable aspectJ annotation -->  
    <!-- 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")  
     -->
   <aop:aspectj-autoproxy proxy-target-class="false"/>

   <context:component-scan base-package="com.synergy.bank.base.aop.logger"/>


Step-3
Define custom annotation for AOP

@Target(METHOD)
@Retention(RUNTIME)
public @interface Loggable {


}


Step-4
Define advice with above Annotation

@Component
@Aspect
public class SynergyDaoLogger {

private static Logger logger=Logger.getLogger(SynergyDaoLogger.class);

@Before("execution(* *(..)) && @annotation(Loggable)")
public void salute(JoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
String methodName = signature.getName();
String arguments = Arrays.toString(joinPoint.getArgs());
if(logger.isDebugEnabled()) {
logger.debug("____________________________________________________________________");
logger.debug("___________Magic of AOP with custom annotation________________");
logger.debug("____________________________________________________________________");

}
}
}


Step-5
Applying logging with custom annotation


@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 @Loggable public List<CustomerEntity> findPendingCustomerList(){ }





1 comment: