Friday, August 24, 2012

Spring Auto-Wiring Beans with @Autowired annotation

In Spring, you can use @Autowired annotation to auto wire bean on the setter method, constructor or a field.

There are two ways to can achieve it :
1.Using <context:annotation-config />
    Just Add Spring context and <context:annotation-config /> in bean configuration file

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

    <context:annotation-config />

</beans>
    
2. Using AutowiredAnnotationBeanPostProcessor
Add 'AutowiredAnnotationBeanPostProcessor' directly in your bean configuration file.

<bean 
class="org.springframework.beans.factory.annotation
.AutowiredAnnotationBeanPostProcessor"/>
 
And in Class, Just add annotation @Autowired above the setter function as seen below , You can do the same on constructor too:
class A {
private B b;

   @Autowired
   public void setB(B b) {
      this.b = b;
   }
}



No comments:

Post a Comment

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...