Spring AOP Example
Aspect Oriented Programming entails breaking down program logic into distinct parts called so-called concerns. The functions that span multiple points of an application are called cross-cutting concerns and these cross-cutting concerns are conceptually separate from the application's business logic
Important Terms
Aspect-A module which has a set of APIs providing cross-cutting requirements.
Join point- This represents a point in your application where you can plug-in AOP aspect
Advice- This is the actual action to be taken either before or after the method execution.
Point cut - This is a set of one or more join points where an advice should be executed
Example
1. Create a class to define aspect module
public class Observer {
/**
* This method will execute before executing any method
*/
public void beforeAdvice(){
System.out.println("Creating employee object");
}
/**
* This method will execute after executing any method
*/
public void afterAdvice(){
System.out.println("Employee object created.");
}
}
2. Create a java entity class
public class Employee {
public Employee() {
System.out.println("Employee constructor executed");
}
private String name;
private String company;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
}
3. Create Beans configuration file (SpringConfig.xml)
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns="http://www.springframework.org/schema/beans"
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:config>
<aop:aspect id="observ" ref="observer" >
<aop:pointcut id="aopPointCutID" expression="execution(* com.pretech.*.*(..))" />
<aop:before method="beforeAdvice" pointcut-ref="aopPointCutID" />
<aop:after method="afterAdvice" pointcut-ref="aopPointCutID" />
</aop:aspect>
</aop:config>
<bean
id="employee"
class="com.pretech.Employee" >
<property
name="name"
value="Raghavan" />
<property
name="company"
value="wipro" />
</bean>
<bean id="observer" class="com.pretech.Observer" />
</beans>
4. Create a Test program (AOPTest.java)
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AOPTest {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("SpringConfig.xml");
Employee employee = (Employee) context.getBean("employee");
employee.getName();
employee.getCompany();
}
}
5. Output
Employee constructor executed
Creating employee object
Employee object created.
Creating employee object
Employee object created.
No comments:
Post a Comment