Categories
Spring Spring Core

Dependency Injection with @Resource annotation

Key Terms

  • As like Autowired annotation Resource will resolve and inject dependencies. 
  • Unlike Autowired annotation, it will search by Name. Means, It will take Field Name and Setter-Method parameter name to resolve dependencies.
  • Name or ID of the Bean should be provided in XML or @Bean configuration.
    • XML <bean id="..." class="..."></bean>
    • @Bean @Bean(“...”)
  • You can provide the name of the Bean in @Resource as a parameter.
    • @Resourse(“...”)
  • If no Name is provided in the parameter of Resource annotation, It will refer to the Field name in case of Field or Setter-Method parameter name in case of Setter-Method
@Resource
public void setElectricalCourse(Course electricalCourse) {
	this.electricalCourse = electricalCourse;
}
  • In the above scenario, it will refer to the electricalCourse from Setter-Method to resolve dependency.
  • If Bean named electricalCource is not found, it will look into its primary type Course to resolve dependencies. Since we have two implementation classes for Course type NoUniqueBeanException will be thrown. 
  • It is always recommended to provide Name or ID to any Bean Definition.
  • Corresponding XML Bean Definition
    • <bean id="electricalCourse" class="example.ElectricalCourseImpl"></bean>
  • It will resolve well known dependencies. Ex., ResourceLoader, ApplicationContext, BeanFactory, MessageSource,…

Limitations of @Resource

  • It supports only Single Arguments. Otherwise it will throw an IllegalStateException at runtime.
  • Not Supported in Constructor even with a single argument. 

Example

I’m using Java 8 and Spring 5.2.6 libraries for this working example. You can copy below Spring maven dependencies.

<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>5.2.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>5.2.6.RELEASE</version>
		</dependency>
</dependencies>
Controller Class

Create a project called ResourceAnnotation and create a CourseController class under example package.

package example;
import javax.annotation.Resource;
public class CourseController {
	@Resource
	private Course computerCourse;
	private Course electricalCourse;
	
	public void listAllDeptCourses() {
		System.out.println("Computer Dept Courses :"+this.getComputerCourse().listOfCoursesByDept());
		System.out.println("Electrical Dept Courses :"+this.getElectricalCourse().listOfCoursesByDept());
	}
	
	/**
	 * @return the computerCourseImpl
	 */
	public Course getComputerCourse() {
		return computerCourse;
	}
	/**
	 * @param computerCourseImpl the computerCourseImpl to set
	 */
	public void setComputerCourse(Course computerCourse) {
		this.computerCourse = computerCourse;
	}
	/**
	 * @return the electricalCourseImpl
	 */
	public Course getElectricalCourse() {
		return electricalCourse;
	}
	/**
	 * @param electricalCourseImpl the electricalCourseImpl to set
	 */
	@Resource
	public void setElectricalCourse(Course electricalCourse) {
		this.electricalCourse = electricalCourse;
	}
}
XML Configuration

Create applicationContext.xml file under src folder and copy below code.

<?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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
	<context:annotation-config />
	<bean id="courseController" class="example.CourseController"></bean>
	<bean id="computerCourse" class="example.ComputerCourseImpl"></bean>
	<bean id="electricalCourse" class="example.ElectricalCourseImpl"></bean>
</beans>
Interface

Create Course interface under example package and copy below code.

package example;
import java.util.List;
public interface Course {
	List<String> listOfCoursesByDept();
}
Implementation Classes

Creating Implementation classes called “ElectricalCourseImpl” and “ComputerCourseImpl” under example package and copy below codes.

ElectricalCourseImpl
package example;
import java.util.ArrayList;
import java.util.List;
public class ElectricalCourseImpl implements Course{
	@Override
	public List<String> listOfCoursesByDept() {
		System.out.println("ElectricalCourseImpl :: listOfCoursesByDept");
		return new ArrayList<String>();
	}
}
ComputerCourseImpl
package example;
import java.util.ArrayList;
import java.util.List;
public class ComputerCourseImpl implements Course {
	@Override
	public List<String> listOfCoursesByDept() {
		System.out.println("ComputerCourseImpl :: listOfCoursesByDept");
		return new ArrayList<String>();
	}
}
Starter class

Create AppStarter class to Initialize IoC and Configure application Bean’s.

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import example.CourseController;
public class AppStarter {
	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		CourseController controller = applicationContext.getBean("courseController", CourseController.class);
		controller.listAllDeptCourses();
		
	}
}

Final Project structure will be like below.

Now run the application from AppStarter class, you can see the below output logged in Eclipse console.

That’s all for now on @Resource annotation in Spring with example…

Happy Reading!!!

Leave a Reply

Your email address will not be published. Required fields are marked *