@Component Annotation in Spring, Spring Autoscan


 

@Component Annotation in Spring, Spring Autoscan

In this tutorial you will learn about auto scanning feature of Spring framework.

In this tutorial you will learn about auto scanning feature of Spring framework.

@Component Annotation in Spring

In Spring normally if there is bean we need to define in the bean configuration file. If you have lot many bean file it is tedious to define all bean in xml configuration so to overcome from this you can scan all your bean through spring auto scan feature. The @Component in StudentDAO class indicates that it is an auto scan component. The @Autowired annotation tell to auto wire the student DAO by type.

StudentDAO.java

package com.roseindia.student.dao;

import org.springframework.stereotype.Component;

@Component
public class StudentDAO {
	@Override
	public String toString() {
		return " inside StudentDAO";
	}
}

StudentService.java

package com.roseindia.student.services;

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

import com.roseindia.student.dao.StudentDAO;

@Component
public class StudentService {
	@Autowired
	StudentDAO studentDAO;

	@Override
	public String toString() {
		return "StudentService [studentDAO=" + studentDAO + "]";
	}
}

MainApp.java

package com.roseindia.common;

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

import com.roseindia.student.services.StudentService;

public class MainApp {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "context.xml" });
		StudentService stud = (StudentService) context
				.getBean("studentService");
		System.out.println(stud);
	}
}

context.xml 

<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-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="com.roseindia.student" />
 
</beans>

When you run this application it will display message as shown below:


StudentService [studentDAO= inside StudentDAO]

Download this example code

Ads