Spring autowiring using @Resource and @Inject annotation example


In the previous tutorial Spring @Autowired annotation example, we have perform the autowiring using @Autowired annotation on field, setter method and constructor. Now in this tutorial, we are going to discuss about autowiring through the @Resource and @Inject annotations. These annotations have the same properties as @Autowired. Check these key points.

@Autowired @Resource @Inject
@Autowired annotation will inject dependent beans automatically. It internally uses the byType mechanism, so there is chance to get ambiguity problem. We can resolve the ambiguity by using @Qualifier annotation. @Resource annotation will also inject dependent beans automatically. It internally uses the byName mechanism, so there is no chance to get ambiguity problem because throughout the whole Spring application bean id name is unique. @Inject annotation is similar to @Autowired. It also uses the byType mechanism internally. So, there is chance to get ambiguity problem. It can also resolve by using @Qualifier annotation.

Note: Autowiring functionality allows you to inject only secondary type’s value, it is not applicable for primitive type’s value. Primitive types value must be inject manually.

Let’s check the snippet of code of these annotations. We are not going to write whole code here because we have similar article for the same check it.

@Resource annotation

@Resource annotation available in javax.annotation package.

ResourceBean.java
package org.websparrow;

import javax.annotation.Resource;

public class ResourceBean {

	@Resource
	private State state;

	public void display() {
		System.out.println("State name is: " + state.getStateName());
	}
}

@Inject annotation

@Inject annotation available in javax.inject package.

InjectBean.java
package org.websparrow;

import javax.inject.Inject;

public class InjectBean {

	@Inject
	private State state;

	public void display() {
		System.out.println("State name is: " + state.getStateName());
	}
}

Share this article on: