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.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"
|
StudentService [studentDAO= inside StudentDAO] |