Spring AOP XML Schema based Example

In this chapter we will see that Implementation of AOP based on XML Schema and also look the relative code in annotation based. Before using the AOP we have to add namespaces of AOP to the configuration file as following.

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

<!-- bean definition & AOP specific configuration -->

</beans>

You will also need following AspectJ libraries on the CLASSPATH of your application. These libraries are available in the ‘lib’ directory of an AspectJ installation, otherwise you can download them from the internet.

1. aspectjrt.jar
2. aspectjweaver.jar
3. aspectj.jar


Declaring an aspect

An aspect is declared using the <aop:aspect> element, and the backing bean is referenced using the ref attribute as follows:

<bean class="com.sdnext.aop.tutorial.aspectJ.LoggingAspect" id="loggingAspect">
  ....
</bean>
<aop:config>
   <aop:aspect id="loggingAspect" ref="loggingAspect">
   ....
   </aop:aspect>
</aop:config>

Here “loggingAspect” will be configured and dependency injected just like any other Spring bean as you have seen in previous chapters.

Declaring a pointcut

A pointcut helps in determining the join points (ie methods) of interest to be executed with different advices. While working with XML Schema based configuration, pointcut will be defined as follows:

<aop:config>
   <aop:aspect id="loggingAspect" ref="loggingAspect">

   <aop:pointcut expression="execution(* com.sdnext.aop.service.*.*(..))" id="businessService"> </aop:pointcut>
   ...
   </aop:aspect>
</aop:config>

<bean class="com.sdnext.aop.tutorial.aspectJ.LoggingAspect" id="loggingAspect">
  ....
</bean>

The following example defines a pointcut named ‘businessService‘ that will match the execution of all getter as like getName() etc method available in Circle class under the package com.sdnext.aop.tutorial:

<aop:config>
   <aop:aspect id="loggingAspect" ref="loggingAspect">

   <aop:pointcut expression="execution(* com.sdnext.aop.tutorial.Circle.getName(..))" id="businessService"></aop:pointcut>
       ....
   </aop:aspect>
</aop:config>

<bean class="com.sdnext.aop.tutorial.aspectJ.LoggingAspect" id="loggingAspect">
  ....
</bean>


Declaring advices

You can declare any of the five advices inside an <aop:aspect>…</aop:aspect> using the <aop: name=”name”>…</aop:>element as given below:

1.before advice- <aop:before></aop:before >
2.after advice- <aop:after></aop:after>
3.after-returning advice- <aop:after-returning></aop:after-returning>
4.after-throwing advice- <aop:after-throwing></aop:after-throwing>
5.around advice- <aop:around></aop:around>

<aop:config>
   <aop:aspect id="loggingAspect" ref="loggingAspect">
      <aop:pointcut expression="execution(* com.sdnext.aop.service.*.*(..))" id="businessService">
     </aop:pointcut>
      <!-- a before advice definition -->
      <aop:before method="someRequiredTask" pointcut-ref="businessService">
        ..... 
     </aop:before>
      <!-- an after advice definition -->
      <aop:after method="someRequiredTask" pointcut-ref="businessService">
         ...... 
      </aop:after>
      <!-- an after-returning advice definition -->
      <!--The someRequiredTask method must have parameter named retVal -->
      <aop:after-returning method="someRequiredTask" pointcut-ref="businessService" returning="retVal">
        ..... 
      </aop:after-returning>
      <!-- an after-throwing advice definition -->
      <!--The someRequiredTask method must have parameter named ex -->
      <aop:after-throwing method="someRequiredTask" pointcut-ref="businessService" throwing="ex">
        ....
       </aop:after-throwing>
      <!-- an around advice definition -->
      <aop:around method="someRequiredTask" pointcut-ref="businessService">
      ...
     </aop:around>
     .....
  </aop:aspect>
</aop:config>

<bean class="com.sdnext.aop.tutorial.aspectJ.LoggingAspect" name="loggingAspect">
  ....
</bean>

You can use same someRequiredTask or different methods for different advices. These methods will be defined as a part of aspect module.
we can also declare the advice as following ways also.

<aop:config>
   <aop:aspect id="loggingAspect" ref="loggingAspect">
     <aop:after method="stringArgumentsMethods" pointcut="args(name)"></aop:after>
     <aop:after-returning method="afterReturningAdvice" pointcut="args(name)" returning="returnString"></aop:after-returning>
    <aop:after-throwing method="exceptionMethod" pointcut="args(name)" throwing="ex">
</aop:after-throwing>
   <aop:around method="myArroundMethod" pointcut="within(com.sdnext.aop.tutorial.model.Circle)"></aop:around>
   <aop:before method="loggingAdvice" pointcut="execution(public * get*(..))"></aop:before>
 </aop:aspect>
</aop:config>

<bean class="com.sdnext.aop.tutorial.aspectJ.LoggingAspect" name="loggingAspect">
  ....
</bean>

Let see how to use the AspectJ annotation with differences advice in the below interface methods and also we compare the XML schema vs Aspect Annotation.

package com.sdnext.aop.aspectj.tutorial;
 
public interface Employee{
 
 void addEmployee();
 
 String addEmployeeReturnValue();
 
 void addEmployeeThrowException() throws Exception;
 
 void addEmployeeAround(String name);
}


1. AspectJ <aop:before> = @Before

package com.sdnext.aop.tutorial.aspectJ;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect
{
//Joint point means a place where advice are applied to target methods
@Before("execution(com.sdnext.aop.aspectj.tutorial.Employee.addEmployee(..))")
public void loggingBoforeAdvice(JoinPoint joinPoint)  
{
  System.out.println(joinPoint.toString());
  //....
  //....
  System.out.println("Advice run. ADD method is called");
}

Its Equivalent functionality writing in XML, with <aop:before>.

<!-- Aspect -->
<bean class="com.sdnext.aop.tutorial.aspectJ.LoggingAspect" name="loggingAspect">
 </bean>
<aop:config>
   <aop:aspect id="loggingAspect" ref="loggingAspect">
      <!-- @Before -->
  <aop:pointcut expression="execution(*com.sdnext.aop.aspectj.tutorial.Employee.addEmployee(..))" id="pointCutBefore"></aop:pointcut>
 
     <aop:before method="loggingBoforeAdvice" pointcut-ref="pointCutBefore"></aop:before>
 
  </aop:aspect>
 
</aop:config>


2. AspectJ <aop:after> = @After

package com.sdnext.aop.tutorial.aspectJ;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.After;

@Aspect
public class LoggingAspect
{
//Joint point means a place where advice are applied to target methods
@After("execution(com.sdnext.aop.aspectj.tutorial.Employee.addEmployee(..))")
public void loggingAfterAdvice(JoinPoint joinPoint)  
{
  System.out.println(joinPoint.toString());
  //....
  //....
  System.out.println("Advice run. ADD method is called");
}

Its Equivalent functionality writing in XML, with <aop:after>.

<!-- Aspect -->
<bean class="com.sdnext.aop.tutorial.aspectJ.LoggingAspect" name="loggingAspect">
 </bean>
<aop:config>
   <aop:aspect id="loggingAspect" ref="loggingAspect">
      <!-- @After -->
  <aop:pointcut expression="execution(*com.sdnext.aop.aspectj.tutorial.Employee.addEmployee(..))" id="pointCutAfter"></aop:pointcut>
 
   <aop:before method="loggingAfterAdvice" pointcut-ref="pointCutAfter"></aop:before>
 
  </aop:aspect>
 
</aop:config>


3. AspectJ <aop:after-returning> = @AfterReturning

package com.sdnext.aop.tutorial.aspectJ;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;

@Aspect
public class LoggingAspect
{
//Joint point means a place where advice are applied to target methods
@AfterReturning(
   pointcut = "execution(* com.sdnext.aop.aspectj.tutorial.Employee.addEmployeeReturnValue(..))",
   returning= "result")
   public void logAfterReturning(JoinPoint joinPoint, Object result) {
 //...
   }
 
}

Its Equivalent functionality writing in XML, with <aop:after-returning>.

<!-- Aspect -->
<bean class="com.sdnext.aop.tutorial.aspectJ.LoggingAspect" name="loggingAspect">
 </bean>
<aop:config>
   <aop:aspect id="loggingAspect" ref="loggingAspect">
      <!-- @AfterReturning -->
    <aop:pointcut expression="execution(* com.sdnext.aop.aspectj.tutorial.Employee.addEmployeeReturnValue(..))" id="pointCutAfterReturning"></aop:pointcut>
 
    <aop:after-returning method="logAfterReturning" pointcut-ref="pointCutAfterReturning" returning="result"> </aop:after-returning>
 
  </aop:aspect>
 
</aop:config>


4. AspectJ <aop:after-throwing> = @AfterThrowing

package com.sdnext.aop.tutorial.aspectJ;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterThrowing;

@Aspect
public class LoggingAspect
{
//Joint point means a place where advice are applied to target methods
@AfterThrowing(
   pointcut = "execution(* com.sdnext.aop.aspectj.tutorial.Employee.addEmployeeThrowException(..))",
    throwing= "error")
   public void logAfterThrowing(JoinPoint joinPoint, Throwable error) {
 //...
  }
}

Its Equivalent functionality writing in XML, with <aop:after-throwing>.

<!-- Aspect -->
<bean class="com.sdnext.aop.tutorial.aspectJ.LoggingAspect" name="loggingAspect">
 </bean>
<aop:config>
   <aop:aspect id="loggingAspect" ref="loggingAspect">
      <!-- @AfterThrowing -->
    <aop:pointcut expression="execution(* com.sdnext.aop.aspectj.tutorial.Employee.addEmployeeThrowException(..))" id="pointCutAfterThrowing">&lt;/
aop:pointcut&gt; 
    <aop:after-thrwoing method="logAfterThrowing" pointcut-ref="pointCutAfterThrowing" throwing="error"></aop:after-thrwoing>
 
  </aop:pointcut></aop:aspect>
 
</aop:config>


5. AspectJ <aop:after-around> = @Around

package com.sdnext.aop.tutorial.aspectJ;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;

@Aspect
public class LoggingAspect
{
//Joint point means a place where advice are applied to target methods
@Around("execution(* com.sdnext.aop.aspectj.tutorial.Employee.addEmployeeAround(..))")
 public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
  //...
 }
}

Its Equivalent functionality writing in XML, with <aop:around>.

<!-- Aspect -->
<bean class="com.sdnext.aop.tutorial.aspectJ.LoggingAspect" name="loggingAspect">
 </bean>
<aop:config>
   <aop:aspect id="loggingAspect" ref="loggingAspect">
     <!-- @Around -->
   <aop:pointcut expression="execution(* com.sdnext.aop.aspectj.tutorial.Employee.addEmployeeAround(..))" id="pointCutAround"></aop:pointcut>
 
   <aop:around method="logAround" pointcut-ref="pointCutAround"></aop:around>
  </aop:aspect>
 
</aop:config>


XML Schema Based AOP Example

To understand above mentioned concepts related to XML Schema Based AOP, let us write an example which will implement few of the advices. To write our example with few advices, let us have working Eclipse IDE in place and follow the following steps to create a Spring application:

Step Description
1 Create a java project with a name SpringAOPDemo and create a package com.dineshonjava.sdnext.aop.aspectJ under the src folder in the created project.
2 Add required Spring libraries using Add External JARs or User Liberaries option .
3 Add Sppring AOP secific libraries aspectjrt.jar, aspectjweaver.jar and aspectj.jar in the project.
4 Create Java classes LoggingAspect, Employee and AopMain under the com.dineshonjava.sdnext.aop.aspect, com.dineshonjava.sdnext.aop.emp,  com.dineshonjava.sdnext.aop package respectively.
5 Create Beans configuration file spring.xml under the src folder.
6 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.
XML Schema based AOP Example

Here is the content of LoggingAspect.java file. This is actually a sample of aspect module which defines methods to be called at various points.

LoggingAspect.java

package com.dineshonjava.sdnext.aop.aspect;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

public class LoggingAspect {
 public void logBeforeAdvice(JoinPoint joinPoint) {

  System.out.println("logBeforeAdvice() is running!");
  System.out.println("hijacked : " + joinPoint.getSignature().getName());
  System.out.println("******");
 }

 public void logAfterAdvice(JoinPoint joinPoint) {

  System.out.println("logAfterAdvice() is running!");
  System.out.println("hijacked : " + joinPoint.getSignature().getName());
  System.out.println("******");

 }
 
 public void logAfterReturningAdvice(JoinPoint joinPoint, Object result) {

  System.out.println("logAfterReturningAdvice() is running!");
  System.out.println("hijacked : " + joinPoint.getSignature().getName());
  System.out.println("Method returned value is : " + result);
  System.out.println("******");

 }
 
 public void logAfterThrowingAdvice(JoinPoint joinPoint, Throwable error) {

  System.out.println("logAfterThrowingAdvice() is running!");
  System.out.println("hijacked : " + joinPoint.getSignature().getName());
  System.out.println("Exception : " + error);
  System.out.println("******");

 }
 
 public void logAroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {

  System.out.println("logAroundAdvice() is running!");
  System.out.println("hijacked method : " + joinPoint.getSignature().getName());
  System.out.println("hijacked arguments : " + Arrays.toString(joinPoint.getArgs()));
  
  System.out.println("Around before is running!");
  joinPoint.proceed();
  System.out.println("Around after is running!");
  
  System.out.println("******");

 }
}

Employee.java

package com.dineshonjava.sdnext.aop.emp;

public interface Employee {
 
 void addEmployee();  
    
  String addEmployeeReturnValue();  
    
  void addEmployeeThrowException() throws Exception;  
    
  void addEmployeeAround(String name);  
}

EmployeeImpl.java

package com.dineshonjava.sdnext.aop.emp.impl;

import com.dineshonjava.sdnext.aop.emp.Employee;

public class EmployeeImpl implements Employee {

 public void addEmployee() {
  System.out.println("addEmployee() is running ");
 }

 public String addEmployeeReturnValue() {
  System.out.println("addEmployeeReturnValue() is running ");
  return "abc";
 }

 public void addEmployeeThrowException() throws Exception {
  System.out.println("addEmployeeThrowException() is running ");
  throw new Exception("Generic Error");
 }

 public void addEmployeeAround(String name) {
  System.out.println("addEmployeeAround() is running, args : " + name);
 }
}

spring.xml

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

 <bean class="com.dineshonjava.sdnext.aop.emp.impl.EmployeeImpl" id="employee"></bean>

    <aop:aspectj-autoproxy>
 <!-- Aspect -->
 <bean class="com.dineshonjava.sdnext.aop.aspect.LoggingAspect" id="logAspect"></bean>

 <aop:config>

  <aop:aspect id="aspectLoggging" ref="logAspect">

   <!-- @Before -->
   <aop:pointcut expression="execution(* com.dineshonjava.sdnext.aop.emp.Employee.addEmployee(..))" id="pointCutBefore"></aop:pointcut>

   <aop:before method="logBeforeAdvice" pointcut-ref="pointCutBefore"></aop:before>
   
   <!-- @After -->
   <aop:pointcut expression="execution(* com.dineshonjava.sdnext.aop.emp.Employee.addEmployee(..))" id="pointCutAfter"></aop:pointcut>

   <aop:after method="logAfterAdvice" pointcut-ref="pointCutAfter"></aop:after>
   
   <!-- @AfterReturning -->
   <aop:pointcut expression="execution(* com.dineshonjava.sdnext.aop.emp.Employee.addEmployeeReturnValue(..))" id="pointCutAfterReturning"></aop:pointcut>

   <aop:after-returning method="logAfterReturningAdvice" pointcut-ref="pointCutAfterReturning" returning="result"></aop:after-returning>
   
   
   <!-- @AfterThrowing -->
   <aop:pointcut expression="execution(* com.dineshonjava.sdnext.aop.emp.Employee.addEmployeeThrowException(..))" id="pointCutAfterThrowing"></aop:pointcut>
   
   <aop:after-throwing method="logAfterThrowingAdvice" pointcut-ref="pointCutAfterThrowing" throwing="error"></aop:after-throwing>
   
   
   <!-- @Around -->
   <aop:pointcut expression="execution(* com.dineshonjava.sdnext.aop.emp.Employee.addEmployeeAround(..))" id="pointCutAround"></aop:pointcut>
   
   <aop:around method="logAroundAdvice" pointcut-ref="pointCutAround"></aop:around>
   
  </aop:aspect>

 </aop:config>
 
</aop:aspectj-autoproxy></beans>

AopMain.java

package com.dineshonjava.sdnext.aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.dineshonjava.sdnext.aop.emp.Employee;

public class AopMain {
 public static void main(String[] args) throws Exception {

  ApplicationContext appContext = new ClassPathXmlApplicationContext("spring.xml");

  Employee employee = (Employee) appContext.getBean("employee");
  employee.addEmployee();
  
  //employee.addEmployeeReturnValue();
  
  //employee.addEmployeeThrowException();
  
  //employee.addEmployeeAround("dinesh");

 }
}

Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message:

Output:
Nov 4, 2012 8:43:29 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@be2358: display name [org.springframework.context.support.ClassPathXmlApplicationContext@be2358]; startup date [Sun Nov 04 20:43:29 IST 2012]; root of context hierarchy
Nov 4, 2012 8:43:30 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Nov 4, 2012 8:43:30 PM org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
INFO: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@be2358]: org.springframework.beans.factory.support.DefaultListableBeanFactory@1b383e9
Nov 4, 2012 8:43:30 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1b383e9: defining beans [employee,org.springframework.aop.config.internalAutoProxyCreator,logAspect,
org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,
org.springframework.aop.aspectj.AspectJPointcutAdvisor#1,
org.springframework.aop.aspectj.AspectJPointcutAdvisor#2,
org.springframework.aop.aspectj.AspectJPointcutAdvisor#3,
org.springframework.aop.aspectj.AspectJPointcutAdvisor#4,
pointCutBefore,pointCutAfter,pointCutAfterReturning,pointCutAfterThrowing,pointCutAround]; 
root of factory hierarchy
logBeforeAdvice() is running!
hijacked : addEmployee
******
addEmployee() is running
logAfterAdvice() is running!
hijacked : addEmployee
******

Spring AOP Related Posts

  1. Spring AOP Interview Questions and Answers
  2. Spring AOP-Introduction to Aspect Oriented Programming
  3. @Aspect Annotation in Spring
  4. Advices in Spring AOP
  5. Spring AOP JoinPoints and Advice Arguments
  6. Spring AOP-Declaring pointcut Expressions with Examples
  7. Spring AOP XML configuration
  8. Spring AOP AspectJ @Before Annotation Advice Example
  9. Spring AOP Before Advice Example using XML Config
  10. Spring AOP AspectJ @After Annotation Advice Example
  11. Spring AOP After Advice Example using XML Config
  12. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  13. Spring AOP After-Returning Advice Example using XML Config
  14. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  15. Spring AOP After Throwing Advice Example using XML Config
  16. Spring AOP AspectJ @Around Annotation Advice Example
  17. Spring AOP Around Advice Example using XML Config
  18. Spring AOP Writing First AspectJ Program in Spring
  19. Spring AOP Proxies in Spring
  20. Spring AOP Transaction Management in Hibernate
  21. Spring Transaction Management
  22. Spring Declarative Transaction Management Example
  23. Spring AOP-Ordering of Aspects with Example


Writing First AspectJ Program in Spring

Spring AOP (Aspect-oriented programming) framework is used to modularize cross-cutting concerns in aspects. Put it simple, it’s just an interceptor to intercept some processes, for example, when a method is execute, Spring AOP can hijack the executing method, and add extra functionality before or after the method execution.

In Spring AOP, 4 type of advices are supported :

  • Before advice – Run before the method execution
  • After returning advice – Run after the method returns a result
  • After throwing advice – Run after the method throws an exception
  • Around advice – Run around the method execution, combine all three advices above.

1. Setting up the project structure:

Launch your preferred IDE (I use STS) and Create New Java Project. And then create the file structure as shown below…

Writing First AspectJ Program in Spring

You need to download all the JARs that are in User Libraries “aspectJ-lib” and add them to the project’s class path. You can find these JARs here: Spring, Commons-logging, aspectjrt, aspectjweaver.

2. Writing our Logging Aspect:

package com.dineshonjava.sdnext.aop.tutorial.aspectJ;

@Aspect
public class LoggingAspect
{
        public void loggingAdvice()
 {
    System.out.println("Advice run. Get method is called");
 }
}

3. Configuring Spring AOP and @AspectJ support:

<beans>
.....
  <bean class="com.dineshonjava.sdnext.aop.tutorial.aspectJ.LoggingAspect" name="loggingAspect"></bean>
.....
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
.....
<aop:config>
   <aop:aspect id="loggingAspect" ref="loggingAspect">
        .....
        <aop:after method="..." pointcut="..."></aop:after>
        .....
    </aop:aspect>
</aop:config>
....
</beans>
Spring supports the @AspectJ annotation style approach and the schema-based approach to implement custom aspects. These two approaches have been explained in detail in the following.
1. XML Schema based : Aspects are implemented using regular classes along with XML based configuration.

2. @AspectJ based : @AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations.

Spring AOP Related Posts

  1. Spring AOP Interview Questions and Answers
  2. Spring AOP-Introduction to Aspect Oriented Programming
  3. @Aspect Annotation in Spring
  4. Advices in Spring AOP
  5. Spring AOP JoinPoints and Advice Arguments
  6. Spring AOP-Declaring pointcut Expressions with Examples
  7. Spring AOP XML configuration
  8. Spring AOP XML Schema based Example
  9. Spring AOP AspectJ @Before Annotation Advice Example
  10. Spring AOP Before Advice Example using XML Config
  11. Spring AOP AspectJ @After Annotation Advice Example
  12. Spring AOP After Advice Example using XML Config
  13. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  14. Spring AOP After-Returning Advice Example using XML Config
  15. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  16. Spring AOP After Throwing Advice Example using XML Config
  17. Spring AOP AspectJ @Around Annotation Advice Example
  18. Spring AOP Around Advice Example using XML Config
  19. Spring AOP Proxies in Spring
  20. Spring AOP Transaction Management in Hibernate
  21. Spring Transaction Management
  22. Spring Declarative Transaction Management Example
  23. Spring AOP-Ordering of Aspects with Example

Setting Up AOP Dependencies

Setting Up AOP Dependencies: For setting up AOP dependencies in spring we have to add AOP related libraries. 

Step 1: Create project for AOP

click File->New->Java Project then get the following windows and give the name of project spring25AOPDemo

Setting Up AOP Dependencies

After writing project name spring25AOPDemo and click on ->finish then project created now we have to add related jar files.


Step 2: Adding Jar files->

right click on project->properties->Java Build Path->Lib->Add Liberarie.. then we get the following windows

Setting Up Spring AOP Dependencies

Now select User Library->Next->User Libraries…->New then we will get the following windows

AOP
After creating user library aspectj-lib then add the following jar files into this user library.

AOP Jars
  • aspectjrt.jar
  • aspectjweaver.jar
  • asm-2.2.3.jar
  • aopalliance.jar
Then select aspectj-lib and click on OK then we get the following windows.
Spring AOP

Spring AOP Related Posts

  1. Spring AOP Interview Questions and Answers
  2. Spring AOP-Introduction to Aspect Oriented Programming
  3. @Aspect Annotation in Spring
  4. Advices in Spring AOP
  5. Spring AOP JoinPoints and Advice Arguments
  6. Spring AOP-Declaring pointcut Expressions with Examples
  7. Spring AOP XML configuration
  8. Spring AOP XML Schema based Example
  9. Spring AOP AspectJ @Before Annotation Advice Example
  10. Spring AOP Before Advice Example using XML Config
  11. Spring AOP AspectJ @After Annotation Advice Example
  12. Spring AOP After Advice Example using XML Config
  13. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  14. Spring AOP After-Returning Advice Example using XML Config
  15. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  16. Spring AOP After Throwing Advice Example using XML Config
  17. Spring AOP AspectJ @Around Annotation Advice Example
  18. Spring AOP Around Advice Example using XML Config
  19. Spring AOP Writing First AspectJ Program in Spring
  20. Spring AOP Proxies in Spring
  21. Spring AOP Transaction Management in Hibernate
  22. Spring Transaction Management
  23. Spring Declarative Transaction Management Example
  24. Spring AOP-Ordering of Aspects with Example

Now our project spring25AOPDemo is created with AOP libraries and spring library . Next chapter we will creating first AOP program.

Spring AOP Introduction to Aspect Oriented Programming

In this Spring AOP Tutorial we are talking about the Aspect Oriented Programming in Short “AOP“, Aspect Oriented Programming is a feature Spring provide in the Dependency Injection, Actually Aspect Oriented Programming  is not only feature but also its different style of programming just like as Object Oriented Programming.

Introduction to Spring AOP

Now I am talking about some other programming before Aspect Oriented Programming…

1. Functional Programming: In older programming language like C, we have used functional programming style like below in figure.

Spring AOP Tutorial
As above see In this style of programming writing code into couple of functions and each function perform unit task and each function call another function as see above and after last function execution then program is completed. But in this style of programming the main problem is complexity, it is very messy style of coding to write big project programming.
2. Object Oriented Programming: In this style of programming we would not think about function when we trying to solve problem by writing code, we would think as individual entities as object when writing the program as below Object A, Object B & Object C…
Aspect Oriented Programming with Spring
Here each object contain member variables and methods to perform individual tasks of each individual entity so this is fine but here is also a problem that not all rectify common procedure in all of the objects as common logging procedure in all as logMessage() method in all.

AOP with Spring
In above see that logMessage() method in each objects no matter how many objects are there so this is not good design of programming each object has repeating method. So to solve this type problem we write the separate entity for logger and called in each objects where we want to add read log message as below.
Aspect Oriented Programming
 For using this logger entity in each object we have to make dependency injection with each beans of business classes or we have use inheritance for accessing logger method of Logger class that is good but couple of problems are also there.

First Problem is doing the design this type of style there too many dependencies with non business object because  logger object does not have any business logic in the project its using just for logging with each objects in the project.

PROBLEMS:

  • To many relationships with the crosscutting objects.
  • Code is still required in the all methods
  • Cannot all be changed at once
CROSS CUTTING CONCERNS: Means non business idea or non business logic its not part of our main problem it is related to below…
  • Security
  • Logging
  • Transaction
To solve the above problems in the Object Oriented Programming we can using Aspect Oriented Programming.
3. Aspects Oriented Programming: In this style of code we are make Aspects means Aspects are also specific classes which some special methods for particular tasks like logging, security and transactions etc.

Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns such as transaction management that cut across multiple types and objects. (Such concerns are often termed crosscutting concerns in AOP literature.)

Aspect-oriented programming entails breaking down program logic into distinct parts (so-called concerns, cohesive areas of functionality). All programming paradigms support some level of grouping and encapsulation of concerns into separate, independent entities by providing abstractions (e.g., procedures, modules, classes, methods) that can be used for implementing, abstracting, and composing these concerns. But some concerns defy these forms of implementation, and are called crosscutting concerns because they “cut across” multiple abstractions in a program.

First we make different Aspects…
 a. Logging Aspect
 b. Transaction Aspect
 c. Security Aspect
 etc… and configure with each of objects as per as our requirement with Aspect Configuration file as see below in figure…

AOP

Aspect Configuration file: Its responsible for configuration for all Aspects with the all object where we want to use. Its configure suppose Logging Aspect for a method in Object A Before or After execution of that method,
 its just like the…..
      –Servlet Filter in Servlet Configuration
      -Trigger in Database
      -Interceptors in Struts or in Spring MVC.

Aspect Configuration tells which aspect apply which method of which class. Aspect Configuration solve our three problems of Object Oriented Programming

  • To many relationships with the crosscutting objects– Only single configuration required for every object where we want to use the crosscutting object like Logging Aspect with using Aspect Configuration file
  • Code is still required in the all methods- No need to code required in all method just put that method on the Aspect Configuration file then code automatically associated with that method and execute Before or After execution of Target Method.
  • Cannot all be changed at once- We can all be changed at once by using Aspect Configuration file. 
aspect

There are only two Steps for using Aspects:
  1. Write Aspects
  2. Configure Aspects where the aspects apply

AOP Terminologies:

  • Aspect: A modularization of a concern that cuts across multiple objects. Transaction management is a good example of a crosscutting concern in J2EE applications. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (@AspectJ style).
  • Join 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. Join point information is available in advice bodies by declaring a parameter of type org.aspectj.lang.JoinPoint.
  • Advice: Action taken by an aspect at a particular join point. Different types of advice include “around,” “before” and “after” advice. Advice types are discussed below. Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors “around” the join point.
  • Pointcut: A predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP: Spring uses the AspectJ pointcut language by default.
  • Introduction: (Also known as an inter-type declaration). Declaring additional methods or fields on behalf of a type. Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any proxied object. For example, you could use an introduction to make a bean implement an IsModified interface, to simplify caching.
  • Target object: Object being advised by one or more aspects. Also referred to as the advised object. Since Spring AOP is implemented using runtime proxies, this object will always be a proxied object.
  • AOP proxy: An object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on). In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy. Proxy creation is transparent to users of the schema-based and @AspectJ styles of aspect declaration introduced in Spring 2.0.
  • Weaving: Linking aspects with other application types or objects to create an advised object. This can be done at compile time (using the AspectJ compiler, for example), load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.

Types of advice:

  • Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).
  • After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.
  • After throwing advice: Advice to be executed if a method exits by throwing an exception.
  • After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).
  • Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.

Spring AOP Related Posts

  1. Spring AOP Interview Questions and Answers
  2. @Aspect Annotation in Spring
  3. Advices in Spring AOP
  4. Spring AOP JoinPoints and Advice Arguments
  5. Spring AOP-Declaring pointcut Expressions with Examples
  6. Spring AOP XML configuration
  7. Spring AOP XML Schema based Example
  8. Spring AOP AspectJ @Before Annotation Advice Example
  9. Spring AOP Before Advice Example using XML Config
  10. Spring AOP AspectJ @After Annotation Advice Example
  11. Spring AOP After Advice Example using XML Config
  12. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  13. Spring AOP After-Returning Advice Example using XML Config
  14. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  15. Spring AOP After Throwing Advice Example using XML Config
  16. Spring AOP AspectJ @Around Annotation Advice Example
  17. Spring AOP Around Advice Example using XML Config
  18. Spring AOP Writing First AspectJ Program in Spring
  19. Spring AOP Proxies in Spring
  20. Spring AOP Transaction Management in Hibernate
  21. Spring Transaction Management
  22. Spring Declarative Transaction Management Example
  23. Spring AOP-Ordering of Aspects with Example

Event Handling in Spring

Spring Framework also provide an another feature to promote loose coupling ,which is Application Event handling. Using Events, an Event publisher object can communicate with other objects without even knowing which object is listen.and event listener can work to event without knowing which object publish the events. Publisher Object that object ,who publish the event or call the event and Listener always listen the events that are occurs.
To make a custom event extends the class with ApplicationEvent class.The ApplicationEventPublisher has contain publishEvent() method that enable to publish ApplicationEvents (Custom Events).Any ApplicationListener that is registered with the onApplicationEvent() method in application,listen the events.
To understand The Event handling Lets illustrate a simple example-

Circle.java

package com.dineshonjava.sdnext.eventHandling.tutorial;

import javax.annotation.Resource;

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;

/**
 * @author Dinesh Rajput
 *
 */
@Controller
public class Circle implements ApplicationEventPublisherAware
{
 private Point             center;
 private ApplicationEventPublisher publisher;
 
 /**
  * @param center the center to set
  */
 @Resource(name="pointB")
 public void setCenter(Point center)
 {
  this.center = center;
 }

 public void draw()
 {
             System.out.println("Circle is Drawn");
             DrawEvent drawEvent = new DrawEvent(this);
             publisher.publishEvent(drawEvent);
 }

 @Override
 public void setApplicationEventPublisher(ApplicationEventPublisher publisher)
 {
  this.publisher = publisher;
 }
}

Point.java

package com.dineshonjava.sdnext.eventHandling.tutorial;

/**
 * @author Dinesh Rajput
 *
 */
public class Point 
{
 private int x;
 private int y;
 /**
  * @return the x
  */
 public int getX() 
 {
  return x;
 }
 /**
  * @param x the x to set
  */
 public void setX(int x) 
 {
  this.x = x;
 }
 /**
  * @return the y
  */
 public int getY()
 {
  return y;
 }
 /**
  * @param y the y to set
  */
 public void setY(int y)
 {
  this.y = y;
 } 
}

MyEventListener.java

package com.dineshonjava.sdnext.eventHandling.tutorial;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class MyEventListener implements ApplicationListener
{

 @Override
 public void onApplicationEvent(ApplicationEvent event) 
 {
  System.out.println(event.toString());
 }

}

DrawEvent.java

package com.dineshonjava.sdnext.eventHandling.tutorial;

import org.springframework.context.ApplicationEvent;

public class DrawEvent extends ApplicationEvent
{

 /**
  * Dinesh Rajput
  */
 private static final long serialVersionUID = 6973014356268900607L;

 public DrawEvent(Object source)
 {
  super(source);
 }
 
 public String toString()
 {
  return "Draw event occurred";
 }
}

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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config></context:annotation-config>
<bean class="com.sdnext.dineshonjava.eventHandling.tutorial.Point" id="pointB">
    <property name="x" value="10"></property>
    <property name="y" value="20"></property>
</bean>
<context:component-scan base-package="com.sdnext.dineshonjava.eventHandling.tutorial"></context:component-scan>
</beans>

DrawingApp.java

package com.dieshonjava.sdnext.eventHandling.tutorial;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Dinesh Rajput
 *
 */
public class DrawingApp
{

 /**
  * @param args
  */
 public static void main(String[] args)
 {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Circle circle = (Circle)context.getBean("circle");
circle.draw();
 }
}

Output:

Circle is Drawn
Draw event occurred

Spring Related Topics you may like

  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example

Using properties files in Spring

Using properties files by MessageSource in Spring: In previous chapters we will discuss about ApplicationContext and BeanFactory. ApplicationContext has some extra functionalities in Spring Framework which Internatiolization, Messaging, Properties file etc.

1. Using org.springframework.context.MessageSource: 
Its using read message in the class files and display message as the output, below given example show how to use properties files with org.springframework.context.MessageSource.

myMessage.properties

greeting=Hello Dinesh!
drawing.circle=Circle is Drawn!

Now to read this properties file in the spring application we have to use the a class name “org.springframework.context.support.ResourceBundleMessageSource” this help to pick the properties files into to the application, this define as bean in the spring configuration file(spring.xml). As follows

spring.xml

<beans xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans">

<context:annotation-config> </context:annotation-config>
<context:component-scan base-package="com.dineshonjava.sdnext.tutorial.property"></context:component-scan>

<bean class="com.dineshonjava.sdnext.tutorial.property.Point" id="center">
 <property name="x" value="20"></property>
 <property name="y" value="0"></property>
</bean>
 
<bean class="org.springframework.context.support.ResourceBundleMessageSource" id="messageSource">
 <property name="basenames">
  <list>
      <value>myMessages</value>
  </list>
 </property>
</bean>

</beans>

Now “messageSource” using as property of the bean circle as follows:

Circle.java

package com.dineshonjava.sdnext.tutorial.property;

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

/**
 * @author Dinesh Rajput
 *
 */
@Component
public class Circle
{
 @Autowired
 private Point center;
 @Autowired
 private MessageSource messageSource;

 /**
  * @param messageSource the messageSource to set
  */
 public void setMessageSource(MessageSource messageSource) 
 {
  this.messageSource = messageSource;
 }

 /**
  * @param center the center to set
  */
 public void setCenter(Point center)
 {
  this.center = center;
 }

 public void draw()
 {
System.out.println(this.messageSource.getMessage("drawing.circle", null, "Default Drawing Greeting", null));
 }
}

In the above class file two property “center” and “messageSource” which autowired with the bean name “circle“. We get the message of the properties file in the draw() method by using following method

org.springframework.context.MessageSource.getMessage(String arg0, Object[] arg1, String arg2, Locale arg3)

where String arg0 give the key of properties file to read its related message. 
as our example we are using “drawing.circle” and “greeting” as keys.

Object[] arg1 is the array of parameters which are applied to the properties file.

Example.

drawing.point=Circle: Point is: ({0}, {1})
Here there are two parameters {0}, {1} passes as
getMessage(“drawing.point”, new Object[]{center.getX(), center.getY()}, “Default Drawing Greeting”, null)
Here center.getX() is replace with the {0}
and center.getY() is replace with the {1}

Point.java

package com.dineshonjava.sdnext.tutorial.property;

/**
 * @author Dinesh Rajput
 *
 */
public class Point 
{
 private int x;
 private int y;
 /**
  * @return the x
  */
 public int getX() 
 {
  return x;
 }
 /**
  * @param x the x to set
  */
 public void setX(int x) 
 {
  this.x = x;
 }
 /**
  * @return the y
  */
 public int getY()
 {
  return y;
 }
 /**
  * @param y the y to set
  */
 public void setY(int y)
 {
  this.y = y;
 } 
}

Now run the following class file.

DrawingApp.java

package com.dineshonjava.sdnext.tutorial.property;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Dinesh Rajput
 *
 */
public class DrawingApp
{

 /**
  * @param args
  */
 public static void main(String[] args)
 {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
System.out.println(context.getMessage("greeting", null, "Default Greeting", null));
Circle circle = (Circle)context.getBean("circle");
shape.draw();
 }
}

If every thing ok then we get the following output:
Output:
Jul 18, 2012 9:04:33 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@758fc9: startup date [Wed Jul 18 21:04:33 IST 2012]; root of context hierarchy
Jul 18, 2012 9:04:33 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jul 18, 2012 9:04:34 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1238bd2: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,circle,center,messageSource,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy

Hello Dinesh!
Circle is Drawn!


Using properties file with parameters:

myMessage.properties

greeting=Hello Dinesh!
drawing.circle=Circle is Drawn!
drawing.point=Circle: Point is: ({0}, {1})

Now make some change in the draw() method of Circle.java file.

public void draw()
{
System.out.println(this.messageSource.getMessage("drawing.circle", null, "Default Drawing Greeting", null));
System.out.println(this.messageSource.getMessage("drawing.point", new Object[]   {center.getX(), center.getY()}, "Default Drawing Greeting", null));
}

After make these change run the main application file then we get the following output:
Hello Dinesh!
Circle is Drawn!
Circle: Point is: (20, 0)


Using properties files in Spring


 

2. Using org.springframework.beans.factory.config.PropertyPlaceholderConfigurer:

If you need to read properties file in your Spring application all you need is to configure a PropertyPlaceholderConfigurer bean in your application context.
Following example shows how to read property values from a properties file named myMessage.properties. This file needs to be in your classpath so Spring can find it.

myMessage.properties

X-axis=20
Y-axis=0

spring.xml

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" id="placeholderConfig">    
<property name="location" value="classpath:myMessage.properties"> 
   
  </property>
</bean>  
<bean class="com.dineshonjava.sdnext.tutorial.property.Point" id="center">
 <property name="x" value="${X-axis}"></property>
 <property name="y" value="${Y-axis}"></property>
</bean>

Notice the placeholderConfig bean. This is where we are instructing Spring container to load the values from myMessage.properties file. You can name your will whatever you like.
Spring Related Topics you may like

  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example

Spring @Component Annotation

The @Component Annotation Indicates that an annotated class is a “component“. Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning. 
The @Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively.
Spring @Component Annotation

 See the following example using component annotation:

Triangle.java

package com.dineshonjava.sdnext.componentstreatypeannotation.tutorail;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

@Component
public class Triangle
{
 private Point pointA;
 private Point pointB;
 private Point pointC;
 
 /**
  * Using @Resource annotation for wiring with bean dependency
  * @param pointA the pointA to set
  */
 @Resource
 public void setPointA(Point pointA) {
  this.pointA = pointA;
 }

 /**
  * Using @Resource annotation for wiring with bean dependency
  * @param pointB the pointB to set
  */
 @Resource
 public void setPointB(Point pointB) {
  this.pointB = pointB;
 }

 /**
  * Using @Resource annotation for wiring with bean dependency
  * @param pointC the pointC to set
  */
 @Resource
 public void setPointC(Point pointC) {
  this.pointC = pointC;
 }

 public void draw()
 {
System.out.println("Drawing Triangle");
System.out.println("PointA is ("+pointA.getX()+", "+pointA.getY()+")");
System.out.println("PointB is ("+pointB.getX()+", "+pointB.getY()+")");
System.out.println("PointC is ("+pointC.getX()+", "+pointC.getY()+")");
 }
}

Here we are using @Component annotation with the Triangle class which auto detect as bean in Spring IoC Container.

Point.java

package com.dineshonjava.sdnext.componentstreatypeannotation.tutorail;

public class Point
{
 private int x;
 private int y;
 /**
  * @return the x
  */
 public int getX() {
  return x;
 }
 /**
  * @param x the x to set
  */
 public void setX(int x) {
  this.x = x;
 }
 /**
  * @return the y
  */
 public int getY() {
  return y;
 }
 /**
  * @param y the y to set
  */
 public void setY(int y) {
  this.y = y;
 }
}

DrawingApp.java

package com.dineshonjava.sdnext.componentstreatypeannotation.tutorail;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Dinesh
 *
 */
public class DrawingApp 
{
 /**
  * @param args
  */
 public static void main(String[] args) 
 {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Triangle triangle= (Triangle) context.getBean("triangle");
triangle.draw();
 }
}

spring.xml

<beans xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans">
  
<bean class="com.dineshonjava.sdnext.componentstreatypeannotation.tutorail.Point" id="pointA">
<property name="x" value="0"></property>
<property name="y" value="0"></property>
</bean>
 
<bean class="com.dineshonjava.sdnext.componentstreatypeannotation.tutorail.Point" id="pointB">
<property name="x" value="-20"></property>
<property name="y" value="0"></property>
</bean>

<bean class="com.dineshonjava.sdnext.componentstreatypeannotation.tutorail.Point" id="pointC">
<property name="x" value="20"></property>
<property name="y" value="0"></property>
</bean> 
  
<context:annotation-config></context:annotation-config>
  
<context:component-scan base-package="com.dineshonjava.sdnext.componentstreatypeannotation.tutorail">
</context:component-scan>
</beans>

Here <context:component-scan/> scan the all classes in the base package given as “com.dineshonjava.sdnext.componentstreatypeannotation.tutorail” which are annotated with the @Component annotation or its specific annotations like @Component, @Repository, @Service & @Controller etc then these classes detect as bean of Spring IoC Container.
If every thing is OK then run that application we will get the following output.
Output:
Jul 14, 2012 8:54:13 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@ab50cd: startup date [Sat Jul 14 20:54:13 IST 2012]; root of context hierarchy
Jul 14, 2012 8:54:13 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jul 14, 2012 8:54:14 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1198891: defining beans [pointA,pointB,pointC,center,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,circle,triangle,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy

Drawing Triangle
PointA is (0, 0)
PointB is (-20, 0)
PointC is (20, 0)

Spring Related Topics you may like

  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example

@PostConstruct and @PreDestroy Annotations in JSR-250 with Spring

In this chapter you will learn how to implement the @PostConstruct and @PreDestroy which work similar to init-method and destroy-method in bean configuration file (spring.xml) describe in earlier chapter or implement the InitializingBean and DisposableBean in your bean class.

To    use    @PostConstruct   and    @PreDestroy    you   have    to    register   the CommonAnnotationBeanPostProcessor   at   bean   configuration   or    specifying   the <context:annotation-config /> in the bean configuration file (spring.xml).

To define setup and teardown for a bean, we simply declare the with init-method and/or destroy-method parameters. The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, destroy-method specifies a method that is called just before a bean is removed from the container.
Note:
The @PostConstruct and @PreDestroy annotation are not belong to Spring, it’s located in the J2ee library – common-annotations.jar
You can use @PostConstruct annotation as an alternate of initialization callback and @PreDestroy annotation as an alternate of destruction callback as explained in the below example.

Circle.java

package com.dineshonjava.sdnext.jsr.tutorial;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

public class Circle
{ 
 private Point center;
 
 @Resource(name="pointB")
 public void setCenter(Point center) 
 {
     this.center = center;
 }
 
 public void draw() 
 {
System.out.println("Circle is drawn of center ("+center.getX()+", "+center.getY()+")");
 }
 
 @PostConstruct
 public void initializeCircle()
 {
     //populates the circle data cache upon initialization...  
     System.out.println("Init of Circle");
 }
 
 @PreDestroy
 public void destroyCircle()
 {
    //clears the circle related cache upon destruction..  
    System.out.println("Destroy of Circle");
 }
}

Point.java

package com.dineshonjava.sdnext.jsr.tutorial;

public class Point
{
 private int x;
 private int y;
 /**
  * @return the x
  */
 public int getX() {
  return x;
 }
 /**
  * @param x the x to set
  */
 public void setX(int x) {
  this.x = x;
 }
 /**
  * @return the y
  */
 public int getY() {
  return y;
 }
 /**
  * @param y the y to set
  */
 public void setY(int y) {
  this.y = y;
 }
}

DrawingApp.java

package com.dineshonjava.sdnext.jsr.tutorial;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Dinesh
 *
 */
public class DrawingApp 
{
 /**
  * @param args
  */
 public static void main(String[] args) 
 {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
context.registerShutdownHook();
Circle circle = (Circle) context.getBean("circle");
circle.draw();
 }
}

By default, Spring will not aware of the @PostConstruct and @PreDestroy annotation. To enable it, you have to either register “CommonAnnotationBeanPostProcessor” or specify the <context:annotation-config /> in bean configuration file(spring.xml),

1. Using CommonAnnotationBeanPostProcessor

spring.xml

<beans xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans">
 
<bean class="com.dineshonjava.sdnext.jsr.tutorial.Circle" id="circle"></bean>
  
<bean class="com.dineshonjava.sdnext.jsr.tutorial.Point" id="pointA">
  <property name="x" value="0"></property>
  <property name="y" value="0"></property>
</bean>

<bean class="com.dineshonjava.sdnext.jsr.tutorial.Point" id="pointB">
  <property name="x" value="-20"></property>
  <property name="y" value="0"></property>
</bean>
  
<bean class="com.dineshonjava.sdnext.jsr.tutorial.Point" id="pointC">
  <property name="x" value="20"></property>
  <property name="y" value="0"></property>
</bean> 

<bean class="com.dineshonjava.sdnext.jsr.tutorial.Point" id="center">
  <property name="x" value="10"></property>
  <property name="y" value="10"></property>
</bean>
  
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"></bean>
</beans>

2. Using <context:annotation-config />

spring.xml

<beans xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans">
 
<bean class="com.dineshonjava.sdnext.jsr.tutorial.Circle" id="circle"></bean>
  
<bean class="com.dineshonjava.sdnext.jsr.tutorial.Point" id="pointA">
  <property name="x" value="0"></property>
  <property name="y" value="0"></property>
</bean>

<bean class="com.dineshonjava.sdnext.jsr.tutorial.Point" id="pointB">
  <property name="x" value="-20"></property>
  <property name="y" value="0"></property>
</bean>
  
<bean class="com.dineshonjava.sdnext.jsr.tutorial.Point" id="pointC">
  <property name="x" value="20"></property>
  <property name="y" value="0"></property>
</bean> 

<bean class="com.dineshonjava.sdnext.jsr.tutorial.Point" id="center">
  <property name="x" value="10"></property>
  <property name="y" value="10"></property>
</bean>
  
<context:annotation-config></context:annotation-config>
</beans>

Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message:

Output:
Jul 14, 2012 1:57:00 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@145d068: startup date [Sat Jul 14 01:57:00 IST 2012]; root of context hierarchy
Jul 14, 2012 1:57:00 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jul 14, 2012 1:57:00 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@4e79f1: defining beans [circle,pointA,pointB,pointC,center,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy

Init of Circle
Circle is drawn of center (-20, 0)
Destroy of Circle

Spring Related Topics you may like

  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example

@Resource Annotation in JSR-250 with Spring Framework

You can use @Resource annotation on fields or setter methods and it works the same as in Java EE 5. The @Resource annotation takes a ‘name‘ attribute which will be interpreted as the bean name to be injected. You can say, it follows by-name autowiring semantics as demonstrated in the below example:

Circle.java

package com.dineshonjava.sdnext.jsr.tutorial;

import javax.annotation.Resource;

public class Circle
{ 
 private Point center;
 
 @Resource(name="pointB")
 public void setCenter(Point center) 
 {
    this.center = center;
 }

 public void draw() 
 {
System.out.println("Circle is drawn of center ("+center.getX()+", "+center.getY()+")");
 }
}

If no “name” is specified explicitly, the default name is derived from the field name or setter method. In case of a field, it takes the field name; in case of a setter method, it takes the bean property name.

Point.java

package com.dineshonjava.sdnext.jsr.tutorial;

public class Point
{
 private int x;
 private int y;
 /**
  * @return the x
  */
 public int getX() {
  return x;
 }
 /**
  * @param x the x to set
  */
 public void setX(int x) {
  this.x = x;
 }
 /**
  * @return the y
  */
 public int getY() {
  return y;
 }
 /**
  * @param y the y to set
  */
 public void setY(int y) {
  this.y = y;
 }
}


DrawingApp.java

package com.dineshonjava.sdnext.jsr.tutorial;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Dinesh
 *
 */
public class DrawingApp 
{
 /**
  * @param args
  */
 public static void main(String[] args) 
 {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Circle circle= (Circle) context.getBean("circle");
circle.draw();
 }
}

spring.xml

<beans xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans">
  
<bean class="com.dineshonjava.sdnext.jsr.tutorial.Circle" id="circle"></bean>
  
<bean class="com.dineshonjava.sdnext.jsr.tutorial.Point" id="pointA">
   <property name="x" value="0"></property>
   <property name="y" value="0"></property>
</bean>
  
<bean class="com.dineshonjava.sdnext.jsr.tutorial.Point" id="pointB">
   <property name="x" value="-20"></property>
   <property name="y" value="0"></property>
</bean>
  
<bean class="com.dineshonjava.sdnext.jsr.tutorial.Point" id="pointC">
   <property name="x" value="20"></property>
   <property name="y" value="0"></property>
</bean> 
  
<bean class="com.dineshonjava.sdnext.jsr.tutorial.Point" id="center">
   <property name="x" value="10"></property>
   <property name="y" value="10"></property>
</bean>
<context:annotation-config></context:annotation-config>
</beans>

Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message:

Output:
Jul 14, 2012 12:40:59 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@ab50cd: startup date [Sat Jul 14 00:40:59 IST 2012]; root of context hierarchy
Jul 14, 2012 12:40:59 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jul 14, 2012 12:41:00 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@bd928a: defining beans [circle,pointA,pointB,pointC,center,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy

Circle is drawn of center (-20, 0)

Spring Related Topics you may like

  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example

Spring @Component, @Repository, @Service and @Controller Stereotype Annotations

In this tutorial we would discuss about the Stereotype Annotations in Spring. Spring @Component, @Repository, @Service and @Controller are Stereotype Annotations. @Component is generic stereotype annotation for any Spring-managed component. In the previous version Spring 2.0 introduce the first Stereotype Annotations name as @Repository. The @Component annotations introduced in Spring 2.5 are really just a continuation of the “stereotype” annotations introduced in Spring 2.0. Stereotype annotations are markers for any class that fulfills a role within an application. This helps remove, or at least greatly reduce, the Spring XML configuration required for these components.
spring certification

These annotations are used to stereotype classes with regard to the application tier that they belong to. Classes that are annotated with one of these annotations will automatically be registered in the Spring application context if <context:component-scan> is in the Spring XML configuration(spring.xml).

The Four Types of Spring Stereotype Components and Their Purposes:
+------------+-----------------------------------------------------+
| Annotation | Meaning                                             |
+------------+-----------------------------------------------------+
| @Component | generic stereotype for any Spring-managed component |
| @Repository| stereotype for persistence layer                    |
| @Service   | stereotype for service layer                        |
| @Controller| stereotype for presentation layer (spring-mvc)      |
+------------+-----------------------------------------------------+

Target:

          Class
Description:

@Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively.

Stereotype Annotations in Spring

@Component
public class Circle
{
    private Point center;
    ----
}

Annotation @Repository:

Target:

          Class
Description:
In Spring 2.0 and later, the @Repository annotation is a marker for any class that fulfills the role or stereotype (also known as Data Access Object or DAO) of a repository. Among the uses of this marker is the automatic translation of exceptions.
A class that serves in the persistence layer of the application as a data access object (DAO), otherwise known as a repository in some other technologies. Annotate all your DAO classes with @Repository. All your database access logic should be in DAO classes.
@Repository
public class CircleDaoImpl implements CircleDao
{
    private Point center;
    ----
}

Annotation @Service:

Target:

          Class
Description:
Annotate all your service classes with @Service. All your business logic should be in Service classes.
@Service
public class CircleServiceImpl implements CircleService
{
    private Point center;
    ----
}

Annotation @Controller:

Target:

          Class
Description:
The @Controller is a class level annotation, which indicates that the annotated class is a Spring component of type “controller“.
The @Controller annotation indicates that a particular class serves the role of a controller. Spring does not require you to extend any controller base class or reference the Servlet API. However, you can still reference Servlet-specific features if you need to. In Spring MVC you can make controller class very easily by prefixing @Controller before any class declaration.
@Controller
public class CircleController
{
    private Point center;
    ----
}

Enable component scanning
Spring by default does not scan means Spring container does create bean for those classes whose annotated with above for stereotype annotations. So we have to enable component scanning explicity by using “context:component-scan” tag in your applicationContext.xml file. So stereotype annotations will be scanned and configured only when they are scanned by DI container of spring framework.

<context:component-scan base-package="com.dineshonjava.app.service" />
<context:component-scan base-package="com.dineshonjava.app.dao" />
<context:component-scan base-package="com.dineshonjava.app.controller" />

The context:component-scan element requires a base-package attribute, the value of base-package attribute should specifies a starting point for a recursive component search. Spring recommends do not use your top package for scanning, so you should declare specific component-scan elements.

Note: If you are using component-scan property for context namespace then you no longer need to declare context:annotation-config, because autowiring is implicitly enabled when component scanning is enabled.

Where to use stereotype annotations?
Always use these annotations over concrete classes; not over interfaces.

  • @Controller annotation is for a class as a Spring Web MVC controller. It is a meta annotation of @Component, so beans annotated with it are automatically imported into the Spring container. If you add the @Controller annotation to a class then you can use handler mappling annotation i.e. @RequestMapping; to map URLs to instance methods of a class.
  • @Service annotation is for a class as a Service of application.
  • @Repository annotation is more suitable annotation that provides additional benefits specifically for DAOs. The @Repository annotation is a meta annotation of the @Component annotation with similar use and functionality. In addition to importing the DAOs into the DI container, it also makes the unchecked exceptions eligible for translation into Spring DataAccessException.
  • @Component should be used when your class does not fall into either of three categories i.e. Controllers, Services and DAOs.
Spring Related Topics you may like

  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example