In Spring Framework normally we register all our components or beans in the XML configuration file. So when program runs spring container scan this XML file for beans and instantiate the bean components as per requirement. In the case of big projects, it's hard to maintain the XML configuration file because the number of beans increase, and xml file become very large.
Spring provides valuable annotations to get rid off this problem. @Component, @Controller, @Service and @Repository are the annotations(stereotypes) used for auto-wiring. @Component is a generic stereotype. @Component tells the container, that this class is treated as a component and will be discoverable at the time of Dependency Injection. Spring container first search the bean declaration inside the XML configuration if it does not find then it will search for the bean annotated with @Component and when find it will instantiate the bean.
To enable auto-wiring mode using annotation you need to write following inside the xml configuration file:
- <context:annotation-config/> : This will tell the container that auto-wiring with annotation is enabled.
- <context:component-scan base-package="com.spring.test.componentExample"/> : Where container will search for beans.
Spring @Component Example:
Person.java
package com.evon.example.componentExample;
import org.springframework.stereotype.Component;
@Component
public class Person {
private String name = "Sumit";
private String email = "testmail@gmail.com";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
ApplicationContext.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:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.evon.example.componentExample"/>
</beans>
Main.java
package com.evon.example.componentExample;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
Person person = (Person)context.getBean("person");
System.out.println("Person's name = " + person.getName());
System.out.println("Person's email = " + person.getEmail());
}
}
Output :
Person's name = Sumit
Person's email = testmail@gmail.com
0 Comment(s)