[原]Java web学习系列之 Java web开发中的Spring框架
2012-02-28 13:16 雪夜&流星 阅读(250) 评论(0) 编辑 收藏 举报Spring是轻量级的IOC和AOP容器框架,通过其核心依赖注入机制,以及AOP的声明式事务管理原理,与持久层框架集合,整合其他的MVC框架集合,以提供更好的轻量级解决方案。
添加Spring核心架包:
添加成功之后就会自动添加一个applicationContext.xml配置文件,里面包含有各种支持文件:
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
</beans>
接着新建entity类:
public class Students implements Serializable {
private String name;
private Integer age;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Integer getAge()
{
return age;
}
public void setAge(Integer age)
{
this.age = age;
}
}
新建dao接口类:
public interface StudentsDAO
{
public void save(Students students);
public List<Students> findById();
}
新建dao接口类的实现类:
public class StudentsDAOImpl implements StudentsDAO {
public List<Students> findById() {
System.out.println("findById");
return null;
}
public void save(Students students) {
System.out.println("Save");
}
}
新建service接口类:
public interface StudentsService {
public void registe(Students students);
public List<Students> showStudents();
}
新建service接口类的实现类:
public class StudentsServiceImpl implements StudentsService{
//封装StudentsDAO
private StudentsDAO studentsDAO = null;
public void registe(Students students) {
studentsDAO.save(students);
}
public List<Students> showStudents() {
studentsDAO.findById();
return null;
}
public StudentsDAO getStudentsDAO() {
return studentsDAO;
}
public void setStudentsDAO(StudentsDAO studentsDAO) {
this.studentsDAO = studentsDAO;
}
}
测试类:
public class TestMain {
public static void main(String[] args) {
//通过 ClassPathXmlApplicationContext 装入 Spring 配置文件到bean中
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//通过getBean()方法访问服务层的方法
StudentsService service = (StudentsService)ctx.getBean("studentsService");
//调用showStudents()方法
service.showStudents();
}
}
applicationContext.xml中的配置信息:
<beans default-autowire="byName"
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="students" class="org.clarck.model.entity.Students">
//注入实体类中的学生信息
<property name="name" value="Clarck" />
<property name="age" value="22" />
</bean>
<bean id="studentsDAO" class="org.clarck.model.dao.impl.StudentsDAOImpl" />
//将studentsDAO方法封装到studentsService中
<bean id="studentsService" class="org.clarck.model.service.impl.StudentsServiceImpl">
<property name="studentsDAO" ref="studentsDAO"></property>
</bean>
</beans>
附:IOC 和 AOP
控制反转模式(也称作依赖性介入)的基本概念是:不创建对象,但是描述创建它们的方式。在代码中不直接与对象和服务连接,但在配置文件中描述哪一个组件需要哪一项服务。
笔记记于:2010-8-25 17:25