Archive

Archive for the ‘Spring’ Category

Spring’s Before and After Advice

November 30, 2010 1 comment

Introduction:

This article makes you bit more knowledgeable in one of the spring’s Aspect Oriented Programming concept advice. In this article we see the simple example for the advice aspect of Spring AOP framework. Before that we have a brief look at some AOP concepts that enrich your understanding.

Aspect:

It’s just like a class in OOPs concepts.

Joint point:

A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.

In real world example, it’s just like a menu items in the menu card.

Pointcut:

Combination of joinpoints which are chosen for execution.

In real world example, it’s just like a meal which is combination of items chosen from menu card.

Target:

The class which is going to be advised.

Advice:

Actions taken by an aspect at a particular joinpoint.The advices are classified into three major groups.

  • Before advice
  • After advice
  • Around advice
Before advice:

Before advice is executed before the execution of methods in the target.

After advice:

After advice is executed after the execution of methods in target. Normally before advice and after advices are used to logging feature. It’s classified into three subgroups.

Types:

  • After returning advice
  • After throwing advice
  • After (finally) advice
Around Advice:

Around advice is executed before and after execution. Its the powerful form of advice. We have a explanation in our next meet.

It is also responsible for choosing whether to proceed to the join point or to block the advised method execution by returning its own return value or throwing an exception. All other advices cannot block the execution flow.

Lets see the example for before and after returning advices.

Prerequisites:

JDK 1.5 and Above

Your favourite IDE

spring latest  jars

commons-logging.jar

spring-aop-1.2.6.jar

SpringAOPInterface.java:

An ordinary interface.

package com.info.spring.aop;
public interface SpringAopInterface
{
public void sayHello(String name);
}

SpringAOPImpl.java:

An ordinary implementation class of an interface SpringAOPInterface.


package com.info.spring.aop;
public class SpringAopImpl implements SpringAopInterface{
 public void sayHello(String name)

{

System.out.println("Hello ,"+name);

}}

BeforeAdvisor.java:

A class which represent the before advise.By implementing the MethodBeforeAdvice interface make the POJO class as a before advisor class.

The action which is wants to perform in the before advise class is define in the override method before().


package com.info.spring.aop;
import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

public class BeforeAdvisor implements MethodBeforeAdvice

{
 public void before(Method method, Object[] os, Object o) throws Throwable

{

System.out.println("Before Advisor called");

}}

AfterAdvisor.java:

A class which represent the after advise.Like a before advisor  class by implementing the AfterReturningAdvice interface make the POJO class as a after advisor class.

The action which is wants to perform in the after advise class is define in the override afterReturning().


package com.info.spring.aop;
import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;
public class AfterAdvisor implements AfterReturningAdvice

{
 public void afterReturning(Object o, Method method, Object[] os, Object o1) throws Throwable

{

System.out.println("After advisor called");

}}

IOC Container Configuration:

This is the context configuration file of the application.Its have to be stored in META-INF folder in src package.

Target: represents the bean class which is going to be advised by the advisors.

Interceptor Names: Represent the advisor classes list.

advice: Represent the advisor class and the pattern of the bean classes which are going to be advised.

applicationContext.xml:


<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"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<!-- Bean configuration -->
<bean id="businesslogicbean">
<property name="proxyInterfaces">
<value>com.info.spring.aop.SpringAopInterface</value>
</property>

<!--Target : Reprsent the bean class which is going to be advised-->
<property name="target" ref "beanTarget" />
<!--Denotes the list of advices-->
<property name="interceptorNames">
<list>
<value>beforeAdvisor</value>
<value>afterAdvisor</value>
</list>
</property>
</bean>

<!-- Bean Classes -->
<bean id="beanTarget" class="com.info.spring.aop.SpringAopImpl"/>

<!-- Advisor pointcut definition for before advice -->
<bean id="beforeAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
 <!--Property which represent the advice-->
 <property name="advice" ref="beforeAdvice"/>

 <!--Pattern fot the class which is going to be advised.
 Here any kind of classes are going to be advised.-->
 <property name="pattern">
 <value>.*</value>
</property>
</bean>
<!-- Advisor pointcut definition for before advice -->
<bean id="afterAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
 <property name="advice" ref="afterAdvice"/>
 <property name="pattern">
 <value>.*</value>
 </property>
 </bean>

  <!-- Advice classes -->
<bean id="beforeAdvice"
class="com.info.spring.aop.BeforeAdvisor/>
<bean id="afterAdvice"
class="com.info.spring.aop.AfterAdvisor"/>
</beans>

Tester.java:

By passing the path of the applicationcontext file to theclass ClassPathXmlApplicationContext,  we can get the instance of Application context.

By the method of getBean() of ApplicationContext,we can retrieve the instance of the bean’s interface.We have to pass the id of the bean as the argument to the method getBean().By using the instance of the bean’s interface we can call the method of the interface which is defined in the bean class.


package com.info.spring.aop;
import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Tester

{
 public static void main(String[] args)

{

// Read the configuration file

ApplicationContext ctx = new ClassPathXmlApplicationContext("META-INF/applicationContext.xml");

 // Instantiate an object

SpringAopInterface springAopInterface =  (SpringAopInterface) ctx.getBean("businesslogicbean");
 // Execute the public method of the bean

springAopInterface.sayHello("Munees");

}}

Thats all folks,I think its give some idea about the spring AOP’s advice aspect.If you feel this article is helpful to you,Don’t forget to leave your footprints(comments) here.

Advertisements

Spring Bean Automatic Detection using context:component-scan element

November 27, 2010 8 comments

Introduction:

In Spring 3.0, the IOC container can be configured in two ways, They are

  • XML Based Configuration
  • Java Based Configuration.

If we go for XML Based Configuration, the sizes of the xml configuration file is so excess for large applications. But we can reduce the size of the xml configuration file by using Spring’s one of the greatest aspect, automatic detection of Spring beans(classes).

This can be achieved by using context:component-scan element in xml configuration file and @component annotation in bean classes. This article deals with spring bean automatic detection using context:component-scan element. Let’s get over that.

Prerequisites:

JDK 1.5 and Above

Your favourite IDE

spring latest  jars

commons-logging.jar

aopalliance.jar

Creation of component using @Component annotation:

By using @component annotation,we can make the bean class as component.By the same way,the below operator bean class make it as component.

Operator.java


package com.bsj.componentscan;

import org.springframework.stereotype.Component;

/**
 * @author Jhothi
 */
@Component("operator")
public class Operator
{
 public int add(int i,int j)
 {
 return i+j;
 }
 public int subtract(int i,int j)
 {
 return i-j;
 }

 public int multiply(int i,int j)
 {
 return i*j;
 }

 public int divide(int i,int j)
 {
 return i/j;
 }
}

By using auto wired feature of spring we can represent our Operator class as dependency of Calculator class.

By using @Autowired annotation we can make the dependency Operator class as Auto wired one.

Calculator.java


package com.bsj.componentscan;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 *
 * @author Jhothi
 */
@Component("calculator")
public class Calculator
{
 @Autowired
 private Operator operator;
 public void calculation(int i, int j)
 {
 System.out.println("i+j : " + operator.add(i, j));
 System.out.println("i-j : " + operator.subtract(i, j));
 System.out.println("i*j : " + operator.multiply(i, j));
 System.out.println("i/j : " + operator.divide(i, j));
 }

 /**
 * @param operator the operator to set
 */
 public void setOperator(Operator operator)
 {
 this.operator = operator;
 }
}

Note:
The component annotation has the name of the component with in the bracket with quotes. The component name is used for detect the bean by the method getBean() of ApplicationContext.For ex,In @Component (“calculator”), calculator is the name of the component.

Container Configuration:

The IOC container configuration xml file is shown below,The container has the <context:component-scan> element and <context:annotation-config/>

<context:annotation-config/> used to intimate the beans of this IOC container are annotation supported.

By pass the base path of the beans as the value of the base-package attribute of context:component-scan element, we can detect the beans and registering their bean definitions automatically without lots of overhead.

The value of base-package attribute is fully qualified package name of the bean classes. We can pass more than one package names by comma separated like the below one.


<context:component-scan base-package="package1, package2"/>

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"
 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:context="http://www.springframework.org/schema/context"
 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.xsd
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/tx/spring-tx.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context.xsd">

 <context:component-scan base-package="com.bsj.componentscan"/>
 <context:annotation-config/>
</beans>

Finally the @component is one of the stereotype annotations. Some other stereotype annotations are avail. They are @Repository, @Service, and @Controller. The next article deals the stereo type annotaions.Before that if you feel this article is helpful to you doesn’t forget to leave your valuable comments.