Spring 框架的搭建及测试

时间:2024-04-14 20:05:20

1、项目结构如下:

Spring 框架的搭建及测试

2、com.sxl.pojos==》Student.java

package com.sxl.pojos;

public class Student {
private int sid;
private String name;
private String pass;
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}

3、com.sxl.dao==》StudentDao.java

package com.sxl.dao;

import com.sxl.pojos.Student;

public class StudentDao {

    public boolean addStudent(Student s) {
System.out.println("添加学生啊:"+s.getSid()+";"+s.getName()+";"+s.getPass());
return false;
}
}

4、com.sxl.service==》StudentService.java

package com.sxl.service;

import com.sxl.dao.StudentDao;
import com.sxl.pojos.Student; public class StudentService {
private StudentDao mydao;
public StudentService() {
//dao=new StudentDao(); } public boolean addUser(Student stu) {
mydao.addStudent(stu);
return false;
} //IOC注入:1.set方式。2.构造函数方式
public StudentDao getMydao() {
return mydao;
} public void setMydao(StudentDao mydao) {
this.mydao = mydao;
}
}

5、com.sxl.tests==》TestSpring.java

package com.sxl.tests;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.sxl.pojos.*;
import com.sxl.service.StudentService; public class TestSpring { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); Student s=(Student) context.getBean("stu");
s.setSid(1);
s.setName("aaa");
s.setPass("123"); StudentService ss=(StudentService) context.getBean("service");
ss.addUser(s); Student s2=(Student) context.getBean("stu");
s2.setSid(2);
s2.setName("vvv");
s2.setPass("123"); System.out.println(s.getSid()+";"+s.getName()+","+s.getPass());
System.out.println(s2.getSid()+";"+s2.getName()+","+s2.getPass());
}
}

6、配置文件: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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="stu" class="com.sxl.pojos.Student" scope="prototype"></bean> <bean id="dao" class="com.sxl.dao.StudentDao"></bean> <bean id="service" class="com.sxl.service.StudentService">
<property name="mydao" ref="dao"></property>
</bean>
</beans>

7、测试结果:

Spring 框架的搭建及测试