spring实例应用(IoC)

今天初步学习了下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!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值