今天初步学习了下spring框架,现在把学习过程总结一下。
一、创建项目
1、项目结构图
2、工程配置文件web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml,/WEB-INF/aspect-spring.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
3、创建业务逻辑接口
package com.intf;
import com.bean.Student;
public interface IGame {
String play(Student stu);
}
4、创建两个接口实现类
[1]
package com.bean;
import com.intf.IGame;
public class LianLianKanGame implements IGame{
public String play(Student stu){
return stu.getName()+" is doing LianLianKanGame now!";
}
}
[2]
package com.bean;
import com.intf.*;
public class PingTuGame implements IGame{
public String play(Student stu){
return stu.getName()+" is doing PingTuGame now!";
}
}
5、创建一个实体类
package com.bean;
public class Student {
private String id;
private String name;
public Student(String id){
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
6、创建applicationContext.xml
<bean id="IGameImpl" class="com.bean.PingTuGame" />
<bean id="stu_default" class="com.bean.Student" >
<!--构造器注入-->
<constructor-arg>
<value>110</value>
</constructor-arg>
<!-- Setter注入-->
<property name="name">
<value>zhaozp</value>
</property>
</bean>
7、创建主测试页面
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@page import="org.springframework.web.context.WebApplicationContext"%>
<%@page import="com.intf.*"%>
<%@page import="com.bean.*"%>
<html><head>
<meta http-equiv="Content-Type" content="text/html charset=utf-8">
<title>Game Start!</title>
</head>
<body>
<%
WebApplicationContext iocBeanFactory =
WebApplicationContextUtils.getWebApplicationContext(application);
Student stu_default = (Student)iocBeanFactory.getBean("stu_default");
IGame game = (IGame)iocBeanFactory.getBean("IGameImpl");
out.println(game.play(stu_default));
%>
</body></html>
运行结果:
zhaozp is doing PingTuGame now!