Video tutorial to demonstrate how to setup Spring Framework environment with Maven using NetBeans IDE
Free Data Structures and Algorithms Course
Showing posts with label Spring Framework. Show all posts
Showing posts with label Spring Framework. Show all posts
How to setup Spring Framework environment with Maven using NetBeans IDE ? (Video Tutorial)
Video tutorial to demonstrate how to setup Spring Framework environment with Maven using NetBeans IDE
How to configure beans in Spring configuration file ? (Video Tutorial)
Video tutorial to demonstrate how to configure beans in Spring configuration file
How AutoWiring works in Spring Framework ?
Program to demonstrate how AutoWiring works in Spring Framework.
In the Spring Framework bean model, beans have relationships with other beans. In order to satisfy these dependencies of injecting one bean into another we use autowire functionality of Spring Framework. In this tutorial we are taking 6 scenarios by which Spring autowires one bean to another. The Scenarios are changed based on Spring Configuration files and rest all the source code given in this tutorial is the same.
In order to run each scenario individually we just change Spring Configuration xml file and rest code remains the same. So for each scenario to run individual we need
1. Employee POJO class which has-a Address class object
2. Address POJO class which will be wired to Employee class through auto-wiring
3. Test class to test the application
4. Scenario based xml file provided below individually for each scenario
Address POJO class -
Employee POJO class -
Scenario 1 - autowire="no"
In the above scenario we are using autowire attribute value as "no". It means we are using no auto-wiring, so we have to provide ref attribute for referring any bean.
Scenario 2 - autowire="byName"
In the above scenario we are using autowire attribute value as "byName". It means we are using auto-wiring based on name of property, so here Employee has a Address property. Here we have a property in Employee by name as : Address address. So when we say that auto-wire by name Spring sees in configuration that whether there is any bean with id equal to name of property. As soon as it finds this property and its matching id, it uses its setter method to set the property .
Scenario 3 - autowire="byType"
In the above scenario we are using autowire attribute value as "byType". It means we are using auto-wiring based on type of property, so here Employee has a Address property. Here we have a property in Employee by type as : com.hubberspot.spring.autowire.Address . So when we say that auto-wire by type Spring sees in configuration that whether there is any bean with class equal to type of property. As soon as it finds any matching, it uses its setter method to set the property.
Scenario 4 - autowire="constructor"
In the above scenario we are using autowire attribute value as "constructor". It means we are using auto-wiring based on constructor arguments , so here Employee has a Address property. Here we have a constructor in Employee class which takes a argument as : Address address. So when we say that auto-wire by constructor Spring sees in configuration that whether there is any bean with id equal to constructor argument. As soon as it finds any matching , it uses its setter method to set the property .
Scenario 5 - p:namespace
Scenario 6 - c:namespace
Scenario 5 and 6 are using p:namespace and c:namespace which have been introduced in Spring 3.1 . In order to use these namespaces we have to first provide these namespace schemas in the header of xml files as :
"xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
After providing the namespace we can directly use it as p:(property name) and c:(constructor argument) which are same like using property and constructor-arg tag.
Test class -
Output of the program :
In the Spring Framework bean model, beans have relationships with other beans. In order to satisfy these dependencies of injecting one bean into another we use autowire functionality of Spring Framework. In this tutorial we are taking 6 scenarios by which Spring autowires one bean to another. The Scenarios are changed based on Spring Configuration files and rest all the source code given in this tutorial is the same.
In order to run each scenario individually we just change Spring Configuration xml file and rest code remains the same. So for each scenario to run individual we need
1. Employee POJO class which has-a Address class object
2. Address POJO class which will be wired to Employee class through auto-wiring
3. Test class to test the application
4. Scenario based xml file provided below individually for each scenario
Address POJO class -
package com.hubberspot.spring.autowire; public class Address { private String street; private String city; private String state; public Address() { } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } }
Employee POJO class -
package com.hubberspot.spring.autowire; // Create a POJO class Employee which has a // Address Object reference as instance variable public class Employee { private String name; private int age; private Address address; public Employee( String name ) { this.name = name; } public Employee( Address address) { this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
Scenario 1 - autowire="no"
|
In the above scenario we are using autowire attribute value as "no". It means we are using no auto-wiring, so we have to provide ref attribute for referring any bean.
Scenario 2 - autowire="byName"
|
In the above scenario we are using autowire attribute value as "byName". It means we are using auto-wiring based on name of property, so here Employee has a Address property. Here we have a property in Employee by name as : Address address. So when we say that auto-wire by name Spring sees in configuration that whether there is any bean with id equal to name of property. As soon as it finds this property and its matching id, it uses its setter method to set the property .
Scenario 3 - autowire="byType"
|
In the above scenario we are using autowire attribute value as "byType". It means we are using auto-wiring based on type of property, so here Employee has a Address property. Here we have a property in Employee by type as : com.hubberspot.spring.autowire.Address . So when we say that auto-wire by type Spring sees in configuration that whether there is any bean with class equal to type of property. As soon as it finds any matching, it uses its setter method to set the property.
Scenario 4 - autowire="constructor"
|
In the above scenario we are using autowire attribute value as "constructor". It means we are using auto-wiring based on constructor arguments , so here Employee has a Address property. Here we have a constructor in Employee class which takes a argument as : Address address. So when we say that auto-wire by constructor Spring sees in configuration that whether there is any bean with id equal to constructor argument. As soon as it finds any matching , it uses its setter method to set the property .
Scenario 5 - p:namespace
|
Scenario 6 - c:namespace
|
Scenario 5 and 6 are using p:namespace and c:namespace which have been introduced in Spring 3.1 . In order to use these namespaces we have to first provide these namespace schemas in the header of xml files as :
"xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
After providing the namespace we can directly use it as p:(property name) and c:(constructor argument) which are same like using property and constructor-arg tag.
Test class -
package com.hubberspot.spring.autowire; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { // ApplicationContext is a Spring interface which // provides with the configuration for an application. // It provides us with all the methods that BeanFactory // provides. It loads the file resources in a older // and generic manner. It helps us to publish events to the // listener registered to it. It also provides quick support // for internationalization. It provides us with the object // requested, it reads the configuration file and provides // us with the necessary object required. // We are using concrete implementation of ApplicationContext // here called as ClassPathXmlApplicationContext because this // bean factory reads the xml file placed in the classpath of // our application. We provide ClassPathXmlApplicationContext // with a configuration file called as spring.xml placed // at classpath of our application. ApplicationContext context = new ClassPathXmlApplicationContext(("spring.xml")); // In order to get a object instantiated for a particular bean // we call getBean() method of ClassPathXmlApplicationContext // passing it the id for which the object is to be needed. // Here getBean() returns an Object. We need to cast it back // to the Employee object. Without implementing new keyword we // have injected object of Employee just by reading an xml // configuration file. Employee employee = (Employee)context.getBean("employee"); System.out.println("The name of Employee is : " + employee.getName()); System.out.println("The age of Employee is : " + employee.getAge()); System.out.println("The address of Employee is : " + employee.getAddress().getStreet() +" "+ employee.getAddress().getCity() +" "+ employee.getAddress().getState()); } }
Output of the program :
How to create beans by invoking a Constructor (Constructor - Injection) in Spring ?.
A video tutorial to demonstrate how to create beans by invoking a Constructor (Constructor - Injection) in Spring.
Click here to download complete source code
Click here to download complete source code
How to configure Java Collections in beans in Spring Framework ?
Program to demonstrate how to configure Java Collections in beans in Spring Framework.
Click here to download complete source code
Click here to download complete source code
How to create a simple hello world example in Spring ?.
Program to demonstrate How to create a simple hello world example in Spring.
Click here to download complete source code
Click here to download complete source code
@Required Annotation in Spring Framework
@Required annotation is placed in Spring API package org.springframework.beans.factory.annotation.* . This annotation is used for checking Spring Dependency. It checks whether properties of bean are set or not. @Required annotation is placed over the setter for the properties which is to be checked for Spring Dependency.
A Spring Bean by the name "RequiredAnnotationBeanPostProcessor" checks if properties annotated with @Required have been set. Before a bean is initialized into a Spring Container this bean post processor checks for properties whether are set or not (marked as @Required).
Let's look at it by a simple example -
(WITHOUT @Required ANNOTATION)
1. Create a class say "Address.java"
2. Create a class say "Employee.java"
3. Create a Spring Configuration file say "spring.xml"
4. Create a Test class say "Test.java"
As we haven't provided Dependency Injection for Address bean in Employee bean. When we run the above Test class the output comes out to be as -
Exception in thread "main" FirstName : Dinesh
java.lang.NullPointerException
at com.hubberspot.spring.ioc.Test.main(Test.java:36)
Its a null pointer exception because Address bean is not set in Employee bean. When we access the properties of Address bean through Address we get null pointer exception.
(WITH @Required ANNOTATION)
1. Create a class say "Address.java"
2. Create a class say "Employee.java" having @Required annotation on Address setter method.
3. Create a Spring Configuration file say "spring.xml" having a tag context:annotation-config for registering RequiredAnnotationBeanPostProcessor which checks if all the bean properties with the @Required annotation have been set.
4. Create a Test class say "Test.java"
As we haven't provided Dependency Injection for Address bean in Employee bean but this time we have marked setter method of Address with @Required annotation. When we run the above Test class the output comes out to be as -
Exception in thread "main" org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'employee' defined in class path resource [spring.xml]:
Initialization of bean failed; nested exception is
org.springframework.beans.factory.BeanInitializationException:
Property 'address' is required for bean 'employee'
It checks this time before initialization of Employee bean that Address bean is not injected and exception is thrown.
A Spring Bean by the name "RequiredAnnotationBeanPostProcessor" checks if properties annotated with @Required have been set. Before a bean is initialized into a Spring Container this bean post processor checks for properties whether are set or not (marked as @Required).
Let's look at it by a simple example -
(WITHOUT @Required ANNOTATION)
1. Create a class say "Address.java"
package com.hubberspot.spring.ioc; public class Address { private String street; private String city; public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
2. Create a class say "Employee.java"
package com.hubberspot.spring.ioc; public class Employee { private String firstName; private Address address; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
3. Create a Spring Configuration file say "spring.xml"
<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean class="com.hubberspot.spring.ioc.Employee" id="employee"> <property name="firstName" value="Dinesh"></property> </bean> <bean class="com.hubberspot.spring.ioc.Address" id="address"> <property name="street" value="Park Street"></property> <property name="city" value="Pune"></property> </bean> </beans>
4. Create a Test class say "Test.java"
package com.hubberspot.spring.ioc; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { // ApplicationContext is a Spring interface which // provides with the configuration for an application. // It provides us with all the methods that BeanFactory // provides. It loads the file resources in a older // and generic manner. It helps us to publish events to the // listener registered to it. It also provides quick support // for internationalization. It provides us with the object // requested, it reads the configuration file and provides // us with the necessary object required. // We are using concrete implementation of ApplicationContext // here called as ClassPathXmlApplicationContext because this // bean factory reads the xml file placed in the classpath of // our application. We provide ClassPathXmlApplicationContext // with a configuration file called as spring.xml placed // at classpath of our application. ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); // In order to get a object instantiated for a particular bean // we call getBean() method of ClassPathXmlApplicationContext // passing it the id for which the object is to be needed. // Here getBean() returns an Object. We need to cast it back // to the Employee object. Without implementing new keyword we // have injected object of Employee just by reading an xml // configuration file. Employee employee = (Employee) context.getBean("employee"); System.out.println("FirstName : " + employee.getFirstName()); System.out.println("Address : " + employee.getAddress().getStreet() + " , " + employee.getAddress().getCity()); } }
As we haven't provided Dependency Injection for Address bean in Employee bean. When we run the above Test class the output comes out to be as -
Exception in thread "main" FirstName : Dinesh
java.lang.NullPointerException
at com.hubberspot.spring.ioc.Test.main(Test.java:36)
Its a null pointer exception because Address bean is not set in Employee bean. When we access the properties of Address bean through Address we get null pointer exception.
(WITH @Required ANNOTATION)
1. Create a class say "Address.java"
package com.hubberspot.spring.ioc; public class Address { private String street; private String city; public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
2. Create a class say "Employee.java" having @Required annotation on Address setter method.
package com.hubberspot.spring.ioc; import org.springframework.beans.factory.annotation.Required; public class Employee { private String firstName; private Address address; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public Address getAddress() { return address; } @Required public void setAddress(Address address) { this.address = address; } }
3. Create a Spring Configuration file say "spring.xml" having a tag context:annotation-config for registering RequiredAnnotationBeanPostProcessor which checks if all the bean properties with the @Required annotation have been set.
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config /> <bean id="employee" class="com.hubberspot.spring.ioc.Employee"> <property name="firstName" value="Dinesh"></property> </bean> <bean id="address" class="com.hubberspot.spring.ioc.Address"> <property name="street" value="Park Street"></property> <property name="city" value="Pune"></property> </bean> </beans>
4. Create a Test class say "Test.java"
package com.hubberspot.spring.ioc; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { // ApplicationContext is a Spring interface which // provides with the configuration for an application. // It provides us with all the methods that BeanFactory // provides. It loads the file resources in a older // and generic manner. It helps us to publish events to the // listener registered to it. It also provides quick support // for internationalization. It provides us with the object // requested, it reads the configuration file and provides // us with the necessary object required. // We are using concrete implementation of ApplicationContext // here called as ClassPathXmlApplicationContext because this // bean factory reads the xml file placed in the classpath of // our application. We provide ClassPathXmlApplicationContext // with a configuration file called as spring.xml placed // at classpath of our application. ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); // In order to get a object instantiated for a particular bean // we call getBean() method of ClassPathXmlApplicationContext // passing it the id for which the object is to be needed. // Here getBean() returns an Object. We need to cast it back // to the Employee object. Without implementing new keyword we // have injected object of Employee just by reading an xml // configuration file. Employee employee = (Employee) context.getBean("employee"); System.out.println("FirstName : " + employee.getFirstName()); System.out.println("Address : " + employee.getAddress().getStreet() + " , " + employee.getAddress().getCity()); } }
As we haven't provided Dependency Injection for Address bean in Employee bean but this time we have marked setter method of Address with @Required annotation. When we run the above Test class the output comes out to be as -
Exception in thread "main" org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'employee' defined in class path resource [spring.xml]:
Initialization of bean failed; nested exception is
org.springframework.beans.factory.BeanInitializationException:
Property 'address' is required for bean 'employee'
It checks this time before initialization of Employee bean that Address bean is not injected and exception is thrown.
Spring Framework in Java
- How to create BeanFactory using XmlBeanFactory in Spring Framework ?.
- How to provide default constructor initialization to a bean using Spring Framework ?.
- How to provide constructor initialization to a bean using type attribute in configuration file of Spring Framework ?.
- How to Create ApplicationContext with ClassPathXmlApplicationContext in Spring Framework ?.
- How to set properties of a bean using Spring xml configuration file in Spring Framework ?.
- How to provide constructor initialization to a bean using constructor-arg tag in configuration file of Spring Framework ?.
- How to provide constructor initialization to a bean using index attribute in configuration file of Spring Framework ?.
- How to provide object dependency injection to a bean using Configuration file in Spring Framework ?.
- How to work with Inner beans using configuration file in a Spring Framework ?.
- How to create a loosely coupled Java application using Spring Frameworks Dependency Injection ?.
- What are various Namespaces in the Spring Configuration File ?.
- How to provide constructor initialization to a bean using name attribute in configuration file of Spring Framework ?.
- How to use init-method and destroy-method attributes in Spring Configuration file ?.
- How to use InitializingBean and DisposableBean interface for initializing and destroying a bean in Spring Framework ?.
- How AutoWiring works in Spring Framework ?
- How to turn on Annotations in Spring Configuration file ?
- How to turn on Auto Scanning of Spring Components for automatic scanning, detecting and instantiating the beans ?.
- How to use @Qualifier annotation in Spring Framework in making bean qualify to auto-wire from multiple beans ?.
- How to use @Component annotation for automatically configuring a Spring bean without using configuration xml file ?.
- How to perform Autowiring in Spring Framework using Annotations ?
- How to filter components in Spring Framework using include-filter and exclude-filter tag ?.
- How to use required attribute in @Autowired annotation in Spring Framework for Dependency Checking ?.
- How to use aliases when referring to a bean in configuration file of Spring Framework ?.
- How to use @Inject annotation in Spring Framework for Dependency Injection ?.
- How to use Java based configuration in Spring Framework without using XML based configuration ?.
- How to implement Before Advice using Classic Spring Proxy-Based AOP in Java ?.
- How to implement After Advice using @AspectJ Annotation-Driven AOP in Java ?.
- How to implement After Returning Advice using Classic Spring Proxy-Based AOP in Java ?.
- How to implement After Throwing Advice using Classic Spring Proxy-Based AOP in Java ?.
- How to implement Around Advice using Classic Spring Proxy-Based AOP in Java ?.
- How to implement Around Advice using @AspectJ Annotation-Driven AOP in Java ?.
- How to implement After Throwing Advice using @AspectJ Annotation-Driven AOP in Java ?.
- How to implement Before Advice using @AspectJ Annotation-Driven AOP in Java ?.
- How to implement After Returning Advice using @AspectJ Annotation-Driven AOP in Java ?.
- @Required Annotation in Spring Framework
How to implement After Returning Advice using @AspectJ Annotation-Driven AOP in Java ?.
A simple application to demonstrate how to implement After Returning Advice using @AspectJ Annotation-Driven AOP in Java.
Step 1:- Create a Interface Sum.java
Step 2:- SumImpl.java Service Implementation Class
Step 3:- After Returning Advice Implementation class
Step 4 :- Spring Configuration file
Step 5:- Test class
Step 1:- Create a Interface Sum.java
package com.hubberspot.aspectj.annotation.afterreturningadvice; // Its a simple interface for the Sum service. // It contains one single method called as addition(). // This method takes in two arguments both of the type // int. public interface Sum { public int addition(int a , int b); }
Step 2:- SumImpl.java Service Implementation Class
package com.hubberspot.aspectj.annotation.afterreturningadvice; // It is the implementation class for the // Sum service. It just calculates and returns // sum of two numbers passed to it as arguments. public class SumImpl implements Sum { @Override public int addition(int a, int b) { System.out.println("Addition method called ..."); return (a + b); } }
Step 3:- After Returning Advice Implementation class
package com.hubberspot.aspectj.annotation.afterreturningadvice; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; //@Aspect annotation treats this Java class as //Aspect. Its not ordinary POJO class. @Aspect public class AfterReturningSumAdvice { // Method afterReturning() is a After Returning advice // implemented by providing @AfterReturning annotation. // This annotation takes in Pointcut expression, which // indicates when this advice executes. // This Pointcut expression tells that afterReturning() advice // will execute after successful return from the method // addition Sum interface. // The after advice takes in JoinPoint and an Object. JoinPoint // which here represents method execution and pointcut expression // takes in returning property and makes it able to store, available // to the afterReturning method. @AfterReturning( pointcut="execution(* com.hubberspot.aspectj.annotation.afterreturningadvice.Sum.addition(..)))" , returning="result") public void afterReturning(JoinPoint joinPoint , Object result) { System.out.println("Sum of two integers after return is : " + result); } }
Step 4 :- Spring Configuration file
<?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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <!-- Implementation Class --> <bean id="sum" class="com.hubberspot.aspectj.annotation.afterreturningadvice.SumImpl" /> <bean id="afterReturningAdvice" class="com.hubberspot.aspectj.annotation.afterreturningadvice.AfterReturningSumAdvice" /> </beans> |
Step 5:- Test class
package com.hubberspot.aspectj.annotation.afterreturningadvice; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SumTest { public static void main(String[] args) { // ApplicationContext is a Spring interface which // provides with the configuration for an application. // It provides us with all the methods that BeanFactory // provides. It loads the file resources in a older // and generic manner. It helps us to publish events to the // listener registered to it. It also provides quick support // for internationalization. It provides us with the object // requested, it reads the configuration file and provides // us with the necessary object required. // We are using concrete implementation of AbstractApplicationContext // here called as ClassPathXmlApplicationContext because this // bean factory reads the xml file placed in the classpath of // our application. We provide ClassPathXmlApplicationContext // with a configuration file called as before_advice.xml placed // at classpath of our application. ApplicationContext context = new ClassPathXmlApplicationContext("after_returning_advice.xml"); // In order to get a object instantiated for a particular bean // we call getBean() method of ClassPathXmlApplicationContext // passing it the id for which the object is to be needed. // Here getBean() returns an Object. We need to cast it back // to the Sum object. Without implementing new keyword we // have injected object of Sum just by reading an xml // configuration file. Sum sum = (Sum)context.getBean("sum"); int result = sum.addition(5, 10); System.out.println("Result = " + result); } }Output of the program :
How to implement Before Advice using @AspectJ Annotation-Driven AOP in Java ?.
A simple application to demonstrate how to implement Before Advice using @AspectJ Annotation-Driven AOP in Java.
Step 1:- Create a Interface Subtraction.java
Step 2:- SubtractionImpl.java Service Implementation Class
Step 3:- Before Advice Implementation class
Step 4 :- Spring Configuration file
Step 5:- Test class
Output of the program :
Step 1:- Create a Interface Subtraction.java
package com.hubberspot.aspectj.annotation.beforeadvice; // Its a simple interface for the Subtraction service. // It contains one single method called as subtract(). // This method takes in two arguments both of the type // int. public interface Subtraction { public void subtract(int a , int b); }
Step 2:- SubtractionImpl.java Service Implementation Class
package com.hubberspot.aspectj.annotation.beforeadvice; // It is the implementation class for the // Subtraction service. It just calculates and prints // subtraction of two numbers passed to it as arguments. // After printing subtraction on the console it just // throws new RuntimeException(). public class SubtractionImpl implements Subtraction { @Override public void subtract(int a, int b) { if(a > b) { System.out.println((a-b)); } else { System.out.println((b-a)); } } }
Step 3:- Before Advice Implementation class
package com.hubberspot.aspectj.annotation.beforeadvice; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; // @Aspect annotation treats this Java class as // Aspect. Its not ordinary POJO class. @Aspect public class BeforeSubtractAdvice { // Method beforeSubtractAdvice() is a before advice // implemented by providing @Before annotation. // This annotation takes in Pointcut expression, which // indicates when this advice executes. // This Pointcut expression tells that beforeSubtractAdvice() // before subtract method of Subtraction interface. // The before advice takes in JoinPoint which here represents // method execution. @Before("execution(* com.hubberspot.aspectj.annotation.beforeadvice.Subtraction.subtract(..))") public void beforeSubtractAdvice(JoinPoint joinPoint) { System.out.println("Call Before Subtract method ... "); } }
Step 4 :- Spring Configuration file
|
Step 5:- Test class
package com.hubberspot.aspectj.annotation.beforeadvice; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SubtractionTest { public static void main(String[] args) { // ApplicationContext is a Spring interface which // provides with the configuration for an application. // It provides us with all the methods that BeanFactory // provides. It loads the file resources in a older // and generic manner. It helps us to publish events to the // listener registered to it. It also provides quick support // for internationalization. It provides us with the object // requested, it reads the configuration file and provides // us with the necessary object required. // We are using concrete implementation of AbstractApplicationContext // here called as ClassPathXmlApplicationContext because this // bean factory reads the xml file placed in the classpath of // our application. We provide ClassPathXmlApplicationContext // with a configuration file called as after_returning_advice.xml placed // at classpath of our application. ApplicationContext context = new ClassPathXmlApplicationContext("before_advice.xml"); // In order to get a object instantiated for a particular bean // we call getBean() method of ClassPathXmlApplicationContext // passing it the id for which the object is to be needed. // Here getBean() returns an Object. We need to cast it back // to the Subtraction object. Without implementing new keyword we // have injected object of Subtraction just by reading an xml // configuration file. Subtraction subtract = (Subtraction)context.getBean("subtract"); subtract.subtract(10, 6); subtract.subtract(5, 10); } }
Output of the program :
How to implement After Throwing Advice using @AspectJ Annotation-Driven AOP in Java ?.
A simple application to demonstrate how to implement After Throwing Advice using @AspectJ Annotation-Driven AOP in Java.
Step 1:- Create a Interface Divide.java
Step 2:- DivisionImpl.java Service Implementation Class
Step 3:- After Throwing Advice Implementation class
Step 4 :- Spring Configuration file
Step 5:- Test class
Output of the program :
Step 1:- Create a Interface Divide.java
package com.hubberspot.aspectj.annotation.afterthrowingadvice; // Its a simple interface for the Division service. // It contains one single method called as divide(). // This method takes in two arguments both of the type // int. public interface Divide { public int divide(int a , int b); }
Step 2:- DivisionImpl.java Service Implementation Class
package com.hubberspot.aspectj.annotation.afterthrowingadvice; // It is the implementation class for the // Division service. It just calculates and returns // division of two numbers passed to it as arguments. // If denominator passed to it as zero than // new ArithmeticException() is thrown. public class DivideImpl implements Divide { @Override public int divide(int a, int b) { if(b != 0) { return a/b; } else { throw new ArithmeticException(); } } }
Step 3:- After Throwing Advice Implementation class
package com.hubberspot.aspectj.annotation.afterthrowingadvice; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; //@Aspect annotation treats this Java class as //Aspect. Its not ordinary POJO class. @Aspect public class AfterThrowingDivideAdvice { // Method afterThrowing() is a After Throwing advice // implemented by providing @AfterThrowing annotation. // This annotation takes in Pointcut expression, which // indicates when this advice executes. // This Pointcut expression tells that afterThrowing() advice // will execute after any exception is thrown from the method // divide of Divide interface. // The after advice takes in JoinPoint and an Object. JoinPoint // which here represents method execution and pointcut expression // takes in throwing property and makes it able to store, available // to the afterThrowing method. @AfterThrowing ( pointcut = "execution(* com.hubberspot.aspectj.annotation.afterthrowingadvice.Divide.divide(..))" , throwing = "exception" ) public void afterThrowing(JoinPoint joinPoint , Throwable exception) { System.out.println("Exception is thrown by divide method : "+ exception); } }
Step 4 :- Spring Configuration file
<?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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <!-- Implementation Class --> <bean id="divide" class="com.hubberspot.aspectj.annotation.afterthrowingadvice.DivideImpl" /> <bean id="afterThrowingAdvice" class="com.hubberspot.aspectj.annotation.afterthrowingadvice.AfterThrowingDivideAdvice" /> </beans> |
Step 5:- Test class
package com.hubberspot.aspectj.annotation.afterthrowingadvice; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class DivisionTest { public static void main(String[] args) { // ApplicationContext is a Spring interface which // provides with the configuration for an application. // It provides us with all the methods that BeanFactory // provides. It loads the file resources in a older // and generic manner. It helps us to publish events to the // listener registered to it. It also provides quick support // for internationalization. It provides us with the object // requested, it reads the configuration file and provides // us with the necessary object required. // We are using concrete implementation of AbstractApplicationContext // here called as ClassPathXmlApplicationContext because this // bean factory reads the xml file placed in the classpath of // our application. We provide ClassPathXmlApplicationContext // with a configuration file called as after_throwing_advice.xml placed // at classpath of our application. ApplicationContext context = new ClassPathXmlApplicationContext("after_throwing_advice.xml"); // In order to get a object instantiated for a particular bean // we call getBean() method of ClassPathXmlApplicationContext // passing it the id for which the object is to be needed. // Here getBean() returns an Object. We need to cast it back // to the Divide object. Without implementing new keyword we // have injected object of Divide just by reading an xml // configuration file. Divide divide = (Divide)context.getBean("divide"); int result = divide.divide(10 , 5); System.out.println("Result = " + result); result = divide.divide(10, 0); System.out.println("Result = " + result); } }
Output of the program :
How to implement Around Advice using @AspectJ Annotation-Driven AOP in Java ?.
A simple application to demonstrate how to implement Around Advice using @AspectJ Annotation-Driven AOP in Java.
Step 1:- Create a Interface Division.java
Step 2:- DivisionImpl.java Service Implementation Class
Step 3:- Around Advice Implementation class
Step 4 :- Spring Configuration file
Step 5:- Test class
Output of the program :
Step 1:- Create a Interface Division.java
package com.hubberspot.aspectj.annotation.aroundadvice; // Its a simple interface for the Division service. // It contains one single method called as divide(). // This method takes in two arguments both of the type // int. public interface Division { public int divide(int a , int b); }
Step 2:- DivisionImpl.java Service Implementation Class
package com.hubberspot.aspectj.annotation.aroundadvice; // It is the implementation class for the // Division service. It just calculates and returns // division of two numbers passed to it as arguments. public class DivisionImpl implements Division { @Override public int divide(int a, int b) { System.out.println("Number are : " + a + ", " + b); return a/b; } }
Step 3:- Around Advice Implementation class
package com.hubberspot.aspectj.annotation.aroundadvice; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; //@Aspect annotation treats this Java class as //Aspect. Its not ordinary POJO class. @Aspect public class AroundDivideAdvice { // Method invoke() is a around advice // implemented by providing @Around annotation. // This annotation takes in Pointcut expression, which // indicates when this advice executes. // This Pointcut expression tells that invoke() advice // will execute around divide method of Division interface. // The after advice takes in ProceedingJoinPoint which // helps in invoking the divide method. // Based on the user inputs the advice decides whether divide should // be called or not. // invoke() methods takes in ProceedingJoinPoint type as a argument // It takes out arguments which user inputs from the ProceedingJoinPoint // and than validate it accordingly. // It also has a proceed() which transfers controls to method being advised. @Around("execution(* com.hubberspot.aspectj.annotation.aroundadvice.Division.divide(..))") public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable { Object arguments[] = joinPoint.getArgs(); int number = ((Integer)arguments[1]).intValue(); if (number == 0) { throw new Exception("Cannot divide with 0.... "); } return joinPoint.proceed(); } }
Step 4 :- Spring Configuration file
<?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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <!-- Implementation Class --> <bean id="divide" class="com.hubberspot.aspectj.annotation.aroundadvice.DivisionImpl" /> <bean id="aroundAdvice" class="com.hubberspot.aspectj.annotation.aroundadvice.AroundDivideAdvice" /> </beans> |
Step 5:- Test class
package com.hubberspot.aspectj.annotation.aroundadvice; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class DivisionTest { public static void main(String[] args) { // ApplicationContext is a Spring interface which // provides with the configuration for an application. // It provides us with all the methods that BeanFactory // provides. It loads the file resources in a older // and generic manner. It helps us to publish events to the // listener registered to it. It also provides quick support // for internationalization. It provides us with the object // requested, it reads the configuration file and provides // us with the necessary object required. // We are using concrete implementation of AbstractApplicationContext // here called as ClassPathXmlApplicationContext because this // bean factory reads the xml file placed in the classpath of // our application. We provide ClassPathXmlApplicationContext // with a configuration file called as around_advice.xml placed // at classpath of our application. ApplicationContext context = new ClassPathXmlApplicationContext("around_advice.xml"); // In order to get a object instantiated for a particular bean // we call getBean() method of ClassPathXmlApplicationContext // passing it the id for which the object is to be needed. // Here getBean() returns an Object. We need to cast it back // to the Divide object. Without implementing new keyword we // have injected object of Divide just by reading an xml // configuration file. Division divide = (Division)context.getBean("divide"); int result = divide.divide(10 , 5); System.out.println("Result = " + result); result = divide.divide(10, 0); System.out.println("Result = " + result); } }
Output of the program :
How to implement Around Advice using Classic Spring Proxy-Based AOP in Java ?.
A simple application to demonstrate how to implement Around Advice using Classic Spring Proxy-Based AOP in Java.
Step 1:- Division.java Interface
Step 2:- DivisionImpl.java Service Implementation Class
Step 3:- Around Advice Implementation class
Step 4 :- Spring Configuration file
Step 5:- Test class
Output of the program :
Step 1:- Division.java Interface
package com.hubberspot.classic.aop.aroundadvice; // Its a simple interface for the Division service. // It contains one single method called as divide(). // This method takes in two arguments both of the type // int. public interface Division { public int divide(int a , int b); }
Step 2:- DivisionImpl.java Service Implementation Class
package com.hubberspot.classic.aop.aroundadvice; // It is the implementation class for the // Division service. It just calculates and returns // division of two numbers passed to it as arguments. public class DivisionImpl implements Division { @Override public int divide(int a, int b) { System.out.println("Number are : " + a + ", " + b); return a/b; } }
Step 3:- Around Advice Implementation class
package com.hubberspot.classic.aop.aroundadvice; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; // This class implements MethodInterceptor interface // having a method by name invoke(). This Around Advice // is implementing both before and after advice simultaneous. // It can also alters the returned value from the advised // method. It allows some post processing to the methods // returned value. // MethodInterceptor has invoke() method which takes in // argument as MethodInvocation. This MethodInvocation object // has a detailed information about the method being intercepted // It has all the information about the arguments of the // method. It also has a method called as proceed() which // transfer call to target method or the intercepted method public class AroundDivisionAdvice implements MethodInterceptor { // invoke() method decides whether divide() method should be // called or not based on the value passed by the user. // If the denominator passed as zero than new exception is // thrown. // methodInvocation.proceed() helps calling the target method // if not called divide method doesnt gets called. @Override public Object invoke(MethodInvocation methodInvocation) throws Throwable { Object args[] = methodInvocation.getArguments(); int number = ((Integer)args[1]).intValue(); if(number == 0) { throw new Exception("Cannot divide with 0."); } return methodInvocation.proceed(); } }
Step 4 :- Spring Configuration file
|
Step 5:- Test class
package com.hubberspot.classic.aop.aroundadvice; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class DivisionTest { public static void main(String[] args) { // ApplicationContext is a Spring interface which // provides with the configuration for an application. // It provides us with all the methods that BeanFactory // provides. It loads the file resources in a older // and generic manner. It helps us to publish events to the // listener registered to it. It also provides quick support // for internationalization. It provides us with the object // requested, it reads the configuration file and provides // us with the necessary object required. // We are using concrete implementation of AbstractApplicationContext // here called as ClassPathXmlApplicationContext because this // bean factory reads the xml file placed in the classpath of // our application. We provide ClassPathXmlApplicationContext // with a configuration file called as around_advice.xml placed // at classpath of our application. ApplicationContext context = new ClassPathXmlApplicationContext("around_advice.xml"); // In order to get a object instantiated for a particular bean // we call getBean() method of ClassPathXmlApplicationContext // passing it the id for which the object is to be needed. // Here getBean() returns an Object. We need to cast it back // to the Divide object. Without implementing new keyword we // have injected object of Divide just by reading an xml // configuration file. Division divide = (Division)context.getBean("divide"); int result = divide.divide(10 , 5); System.out.println("Result = " + result); result = divide.divide(10, 0); System.out.println("Result = " + result); } }
Output of the program :
Subscribe to:
Posts (Atom)