Xml for spring Injection
1. Inject xml into xml for configuration
Note: The spring container is executing code
ApplicationContext ctx = new ClassPathXmlApplicationContext (beans. xml );
Key Note: bean name is unique and described in xml file
Type 2 diagram
The directory structure is shown in. Here we only test studentService.
Dao level
PackageCom. bjsxt. dao;
ImportCom. bjsxt. model .*;
Public interfaceStudentDao {
Public voidStudentSave (Student s );
}
Impl Layer
PackageCom. bjsxt. dao. impl;
ImportCom. bjsxt. dao .*;
ImportCom. bjsxt. model. Student;
Public classStudentDaoImplImplementsStudentDao {
@ Override
Public voidStudentSave (Student s ){
System.Out. Println (student saved !);
}
}
PackageCom. bjsxt. model;
Public classStudent {
Private intId;
PrivateStringname;
Public voidInit ()
{
System.Out. Println (initialization ......);
}
Public intGetId (){
ReturnId;
}
Public voidSetId (IntId ){
This. Id = id;
}
PublicString getName (){
ReturnName;
}
Public voidSetName (String name ){
This. Name = name;
}
Public voidDestroy ()
{
System.Out. Println (destroy ....);
}
}
PackageCom. bjsxt. service;
ImportCom. bjsxt. dao .*;
Import Com. bjsxt. dao. impl.*;
ImportCom. bjsxt. model .*;
Public classStudentService {
PrivateStudentDaostudentDao;
// Reduces coupling: StudentService does not know who will save the student'sIocContainer to control assembly
PublicStudentDao getStudentDao (){
ReturnStudentDao;
}
Public voidSetStudentDao (StudentDao studentDao ){
This. StudentDao = studentDao;
}
Public voidAdd (Student s)
{
This. StudentDao. StudentSave (s );
}
}
Test class
PackageCom. bjsxt. service;
ImportOrg. junit. Test;
ImportOrg. springframework. context. ApplicationContext;
ImportOrg. springframework. context. support. ClassPathXmlApplicationContext;
ImportCom. bjsxt. model. Student;
Public classStudentServiceTest {
@ Test
Public voidTest (){
System.Out. Println (before running the program ....);
ApplicationContext ctx =NewClassPathXmlApplicationContext (beans. xml );
System.Out. Println (program running starts ....);
StudentService sService = (StudentService) ctx. getBean (studentService );
Student student = (Student) ctx. getBean (student );
Student student2 = (Student) ctx. getBean (student );
System.Out. Println (student2 = student );
SService. add (student );
}
}