Spring Auto Components Scanning Example

You have to annotate with @Component to indicate this is an auto scan component.
Student.java File
package com.jtechies;

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

@Component
public class Student {
	private String name;
	@Autowired 
	private Course course;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Course getCourse() {
		return course;
	}
	public void setCourse(Course course) {
		this.course = course;
	}
}
Course.java File
package com.jtechies;

import org.springframework.stereotype.Component;

@Component
public class Course {
	private String name;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}	
}
Test.java File
package com.jtechies.test;

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

import com.jtechies.Course;
import com.jtechies.Student;

public class Test {
	public static void main(String[] args) {
		ApplicationContext context = new
			ClassPathXmlApplicationContext("spring.xml");
		Course course = (Course)context.getBean("course");
		course.setName("MCA");
		Student student = (Student)
			context.getBean("student");
		System.out.println("course name =
			"+student.getCourse().getName());
	}
}
spring.xml File
<?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 
	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">

<!-- base-package indicates where your component stored,	spring 
	will scan this folder and find out the bean annotated 
	with @Component -->
	<context:component-scan base-package="com.jtechies" />
	
</beans>
Output
course name = MCA

Custom auto scan component name and types of components scan annotation

By default, Spring convert the first character of component into lower case. TO create a custom name for component, use @Service annotation
@Service("myStudent")
public class Student
There are 4 types of auto components scan annotation types:
  • @Component Indicates a auto scan component.
  • @Repository Indicates DAO component in the persistence layer.
  • @Service Indicates the service component in the business layer.
  • @Controller Indicates a controller component in the presentation layer.