Spring - @Resource annotation example

Posted on February 2, 2017


Technologies used:   JDK 1.8.0_121 | Spring 4.3.5.RELEASE | Maven 3.3.9 | Eclipse Mars.2 (4.5.2)

The JSR 250 @Resource annotation is used to mark a reference as a resource. This annotation may be applied on class, field and method.

Spring supports injection using the @Resource annotation, when it is applied on a field or setter method of a bean.

The @Resource annotation follows by-name semantics i.e. it takes a name attribute for injection, which is analogous to ‘autowiring by Name’ in XML based configuration.

 In this post, we will show you how the @Resource annotation works in spring application.

Consider the following beans - BeanOne and BeanTwo.

BeanTwo is injected into BeanOne by applying @Resource over the setter method of the BeanOne  class as follows.

BeanOne.java

package com.boraji.tutorial.spring;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

@Component
public class BeanOne {
   
   private BeanTwo beanTwo;

   @Resource
   public void setBeanTwo(BeanTwo beanTwo) {
      this.beanTwo = beanTwo;
   }
   
   public void doSomething(){
      System.out.println("Inside do doSomething() method of BeanOne");
      beanTwo.doSomething();
   }
}

BeanTwo.java

package com.boraji.tutorial.spring;

import org.springframework.stereotype.Component;

@Component
public class BeanTwo {
   public void doSomething() {
      System.out.println("Inside do doSomething() method of BeanTwo");
   }
}

Create a java based configuration class annotated with @Configuration and @ComponentScan as follows.

AppConfig.java

package com.boraji.tutorial.spring;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.boraji.tutorial.spring")
public class AppConfig {

}

The @ComponentScan annotation scans all beans, whose class is annotated by the @Component annotation in a package, specified by basePackages attribute.

 

Create Main class and run application.

MainApp.java

package com.boraji.tutorial.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author imssbora
 */
public class MainApp {
   public static void main(String[] args) {
      AnnotationConfigApplicationContext context = 
            new AnnotationConfigApplicationContext(AppConfig.class);
      
      BeanOne beanOne = context.getBean(BeanOne.class);
      beanOne.doSomething();
      
      context.close();
   }
}

Output

Inside do doSomething() method of BeanOne
Inside do doSomething() method of BeanTwo