Friday, May 21, 2010

Spring - How to use Component and Autowired

Just put together a sample which made me understand how to use the above mentioned annotations defined by Spring hence thought i should blog about the same.

First lets take a look at the two classes that are exposed as spring beans.

package chapter3;

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

public class Calculator {
private Adder adder;

public void setAdder(Adder adder) {
this.adder = adder;

public void makeAnOperation(){
int r1 = adder.add(1,2);
System.out.println("r1 = " + r1);

package chapter3;

import org.springframework.stereotype.Component;

public class Adder {
public int add(int a, int b){
return a + b;

Few pointers to note here are as follows;

  • By annotation the class with @Component you tell the Spring container that these beans are needed to be instantiated and managed by the Spring container. This reduces XML configurations required because you do not need to manually edit the XML file entering bean definitions to each and every bean.
  • The @Autowired element binds an instance of the Adder class when the Spring container scans the Calculator class.
Next we look at the application context XML

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

<context:component-scan base-package="chapter3"/>


And finally to run the sample following is the main class;

package chapter3;

import org.springframework.context.ApplicationContext;

public class ComponentCheck {

public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext(
Calculator calculator = (Calculator) appContext.getBean("calculator");



No comments:

Post a Comment