Friday, May 21, 2010 0 comments

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;

@Component("calculator")
public class Calculator {
private Adder adder;

@Autowired
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;

@Component("adder")
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="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
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-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

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

</beans>


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



package chapter3;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ComponentCheck {

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

}

}

0 comments

For all your CSS needs

Check this out. Has so many tutorials and designs that you can use or just learn the true power of CSS. Great site.
 
;